Springboot源碼分析之jar探秘

摘要:

  • 利用IDEA等工具打包會(huì)出現(xiàn)springboot-0.0.1-SNAPSHOT.jar,springboot-0.0.1-SNAPSHOT.jar.original,前面說過它們之間的關(guān)系了,接下來我們就一探究竟,它們之間到底有什么聯(lián)系。

文件對(duì)比:

  • 進(jìn)入target目錄,unzip springboot-0.0.1-SNAPSHOT.jar -d jar命令將springboot-0.0.1-SNAPSHOT.jar解壓到j(luò)ar目錄


    file
  • 進(jìn)入target目錄,unzip springboot-0.0.1-SNAPSHOT.jar.original -d original命令將springboot-0.0.1-SNAPSHOT.jar.original解壓到original目錄


    file

前面文章分析過springboot-0.0.1-SNAPSHOT.jar.original不能執(zhí)行,將它進(jìn)行repackage后生成springboot-0.0.1-SNAPSHOT.jar就成了我們的可執(zhí)行fat jar,對(duì)比上面文件會(huì)發(fā)現(xiàn)可執(zhí)行 fat jar和original jar目錄不一樣,最關(guān)鍵的地方是多了org.springframework.boot.loader這個(gè)包,這個(gè)就是我們平時(shí)java -jar springboot-0.0.1-SNAPSHOT.jar命令啟動(dòng)的奧妙所在。MANIFEST.MF文件里面的內(nèi)容包含了很多關(guān)鍵的信息

Manifest-Version: 1.0
Start-Class: com.github.dqqzj.springboot.SpringbootApplication
Spring-Boot-Classes: BOOT-INF/classes/
Spring-Boot-Lib: BOOT-INF/lib/
Build-Jdk-Spec: 1.8
Spring-Boot-Version: 2.1.6.RELEASE
Created-By: Maven Archiver 3.4.0
Main-Class: org.springframework.boot.loader.JarLauncher

相信不用多說大家都能明白Main-Class: org.springframework.boot.loader.JarLauncher是我們 java -jar命令啟動(dòng)的入口,后續(xù)會(huì)進(jìn)行分析,Start-Class: com.github.dqqzj.springboot.SpringbootApplication才是我們程序的入口主函數(shù)。

Springboot jar啟動(dòng)源碼分析

public class JarLauncher extends ExecutableArchiveLauncher {
    static final String BOOT_INF_CLASSES = "BOOT-INF/classes/";
    static final String BOOT_INF_LIB = "BOOT-INF/lib/";

    public JarLauncher() {
    }

    protected JarLauncher(Archive archive) {
        super(archive);
    }
   /**
    * 判斷是否歸檔文件還是文件系統(tǒng)的目錄 可以猜想基于文件系統(tǒng)一樣是可以啟動(dòng)的
    */
    protected boolean isNestedArchive(Entry entry) {
        return entry.isDirectory() ? entry.getName().equals("BOOT-INF/classes/") : entry.getName().startsWith("BOOT-INF/lib/");
    }

    public static void main(String[] args) throws Exception {
    /**
     * 進(jìn)入父類初始化構(gòu)造器ExecutableArchiveLauncher
     * launch方法交給Launcher執(zhí)行
     */
        (new JarLauncher()).launch(args);
    }
}

public abstract class ExecutableArchiveLauncher extends Launcher {
    private final Archive archive;

    public ExecutableArchiveLauncher() {
        try {
    /**
     * 使用父類Launcher加載資源,包括BOOT-INF的classes和lib下面的所有歸檔文件
     */
            this.archive = this.createArchive();
        } catch (Exception var2) {
            throw new IllegalStateException(var2);
        }
    }

    protected ExecutableArchiveLauncher(Archive archive) {
        this.archive = archive;
    }

    protected final Archive getArchive() {
        return this.archive;
    }
    /**
     * 從歸檔文件中獲取我們的應(yīng)用程序主函數(shù)
     */
    protected String getMainClass() throws Exception {
        Manifest manifest = this.archive.getManifest();
        String mainClass = null;
        if (manifest != null) {
            mainClass = manifest.getMainAttributes().getValue("Start-Class");
        }

        if (mainClass == null) {
            throw new IllegalStateException("No 'Start-Class' manifest entry specified in " + this);
        } else {
            return mainClass;
        }
    }

    protected List<Archive> getClassPathArchives() throws Exception {
        List<Archive> archives = new ArrayList(this.archive.getNestedArchives(this::isNestedArchive));
        this.postProcessClassPathArchives(archives);
        return archives;
    }

    protected abstract boolean isNestedArchive(Entry entry);

    protected void postProcessClassPathArchives(List<Archive> archives) throws Exception {
    }
}

public abstract class Launcher {
    public Launcher() {
    }

    protected void launch(String[] args) throws Exception {
      /**
       *注冊(cè)協(xié)議處理器,由于Springboot是 jar in jar 所以要重寫jar協(xié)議才能讀取歸檔文件
       */
        JarFile.registerUrlProtocolHandler();
        ClassLoader classLoader = this.createClassLoader(this.getClassPathArchives());
      /**
       * this.getMainClass()交給子類ExecutableArchiveLauncher實(shí)現(xiàn)
       */
        this.launch(args, this.getMainClass(), classLoader);
    }

    protected ClassLoader createClassLoader(List<Archive> archives) throws Exception {
        List<URL> urls = new ArrayList(archives.size());
        Iterator var3 = archives.iterator();

        while(var3.hasNext()) {
            Archive archive = (Archive)var3.next();
            urls.add(archive.getUrl());
        }

        return this.createClassLoader((URL[])urls.toArray(new URL[0]));
    }
    /**
     * 該類加載器是fat jar的關(guān)鍵的一處,因?yàn)閭鹘y(tǒng)的類加載器無法讀取jar in jar模型,所以springboot進(jìn)行了自己實(shí)現(xiàn)
     */
    protected ClassLoader createClassLoader(URL[] urls) throws Exception {
        return new LaunchedURLClassLoader(urls, this.getClass().getClassLoader());
    }
   
    protected void launch(String[] args, String mainClass, ClassLoader classLoader) throws Exception {
        Thread.currentThread().setContextClassLoader(classLoader);
        this.createMainMethodRunner(mainClass, args, classLoader).run();
    }
    /**
     * 創(chuàng)建應(yīng)用程序主函數(shù)運(yùn)行器
     */
    protected MainMethodRunner createMainMethodRunner(String mainClass, String[] args, ClassLoader classLoader) {
        return new MainMethodRunner(mainClass, args);
    }

    protected abstract String getMainClass() throws Exception;

    protected abstract List<Archive> getClassPathArchives() throws Exception;
   /**
          * 得到我們的啟動(dòng)jar的歸檔文件
            */
    protected final Archive createArchive() throws Exception {
        ProtectionDomain protectionDomain = this.getClass().getProtectionDomain();
        CodeSource codeSource = protectionDomain.getCodeSource();
        URI location = codeSource != null ? codeSource.getLocation().toURI() : null;
        String path = location != null ? location.getSchemeSpecificPart() : null;
        if (path == null) {
            throw new IllegalStateException("Unable to determine code source archive");
        } else {
            File root = new File(path);
            if (!root.exists()) {
                throw new IllegalStateException("Unable to determine code source archive from " + root);
            } else {
                return (Archive)(root.isDirectory() ? new ExplodedArchive(root) : new JarFileArchive(root));
            }
        }
    }
}

public class MainMethodRunner {
    private final String mainClassName;
    private final String[] args;
   
    public MainMethodRunner(String mainClass, String[] args) {
        this.mainClassName = mainClass;
        this.args = args != null ? (String[])args.clone() : null;
    }
    /**
     * 最終執(zhí)行的方法,可以發(fā)現(xiàn)是利用的反射調(diào)用的我們應(yīng)用程序的主函數(shù)
     */
    public void run() throws Exception {
        Class<?> mainClass = Thread.currentThread().getContextClassLoader().loadClass(this.mainClassName);
        Method mainMethod = mainClass.getDeclaredMethod("main", String[].class);
        mainMethod.invoke((Object)null, this.args);
    }
}

小結(jié):

內(nèi)容太多了,未涉及歸檔文件,協(xié)議處理器,打包war同樣的可以用命令啟動(dòng)等,感興趣的讀者請(qǐng)親自去調(diào)試一番,添加依賴

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-loader</artifactId>
        </dependency>

IDEA進(jìn)行啟動(dòng)類的配置


file
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容