当前位置: 欣欣网 > 码农

面试官:为什么SpringBoot的 jar 可以直接运行?

2024-03-22码农

来源:http://fangjian0423.github.io/

SpringBoot提供了一个插件spring-boot-maven-plugin用于把程序打包成一个可执行的jar包。在pom文件里加入这个插件即可:

<build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build>

打包完生成的executable-jar-1.0-SNAPSHOT.jar内部的结构如下:

├── META-INF│ ├── MANIFEST.MF│ └── maven│ └── spring.study│ └── executable-jar│ ├── pom.properties│ └── pom.xml├── lib│ ├── aopalliance-1.0.jar│ ├── classmate-1.1.0.jar│ ├── spring-boot-1.3.5.RELEASE.jar│ ├── spring-boot-autoconfigure-1.3.5.RELEASE.jar│ ├── ...├── org│ └── springframework│ └── boot│ └── loader│ ├── ExecutableArchiveLauncher$1. class│ ├── ...└── spring └── study └── executablejar └── ExecutableJarApplication. class

然后可以直接执行jar包就能启动程序了:

java -jar executable-jar-1.0-SNAPSHOT.jar

打包出来fat jar内部有4种文件类型:

  • META-INF文件夹:程序入口,其中MANIFEST.MF用于描述jar包的信息

  • lib目录:放置第三方依赖的jar包,比如springboot的一些jar包

  • spring boot loader相关的代码

  • 模块自身的代码

  • MANIFEST.MF文件的内容:

    Manifest-Version: 1.0Implementation-Title: executable-jarImplementation-Version: 1.0-SNAPSHOTArchiver-Version: PlexusArchiverBuilt-By: FormatStart- class: spring.study.executablejar.ExecutableJarApplicationImplementation-Vendor-Id: spring.studySpring-Boot-Version: 1.3.5.RELEASECreated-By: ApacheMaven 3.2.3Build-Jdk: 1.8.0_20Implementation-Vendor: PivotalSoftware, Inc.Main- class: org.springframework.boot.loader.JarLauncher

    我们看到,它的Main- class是org.springframework.boot.loader.JarLauncher,当我们使用java -jar执行jar包的时候会调用JarLauncher的main方法,而不是我们编写的SpringApplication。

    那么JarLauncher这个类是的作用是什么的?

    它是SpringBoot内部提供的工具Spring Boot Loader提供的一个用于执行Application类的工具类(fat jar内部有spring loader相关的代码就是因为这里用到了)。相当于Spring Boot Loader提供了一套标准用于执行SpringBoot打包出来的jar

    # Spring Boot Loader抽象的一些类

    抽象类Launcher:各种Launcher的基础抽象类,用于启动应用程序;跟Archive配合使用;目前有3种实现,分别是JarLauncher、WarLauncher以及PropertiesLauncher

    Archive:归档文件的基础抽象类。JarFileArchive就是jar包文件的抽象。它提供了一些方法比如getUrl会返回这个Archive对应的URL;getManifest方法会获得Manifest数据等。ExplodedArchive是文件目录的抽象

    JarFile:对jar包的封装,每个JarFileArchive都会对应一个JarFile。JarFile被构造的时候会解析内部结构,去获取jar包里的各个文件或文件夹,这些文件或文件夹会被封装到Entry中,也存储在JarFileArchive中。如果Entry是个jar,会解析成JarFileArchive。

    比如一个JarFileArchive对应的URL为:

    jar:file:/Users/format/Develop/gitrepository/springboot-analysis/springboot-executable-jar/target/executable-jar-1.0-SNAPSHOT.jar!/

    它对应的JarFile为:

    /Users/format/Develop/gitrepository/springboot-analysis/springboot-executable-jar/target/executable-jar-1.0-SNAPSHOT.jar

    这个JarFile有很多Entry,比如:

    META-INF/META-INF/MANIFEST.MFspring/spring/study/....spring/study/executablejar/ExecutableJarApplication. classlib/spring-boot-starter-1.3.5.RELEASE.jarlib/spring-boot-1.3.5.RELEASE.jar...

    JarFileArchive内部的一些依赖jar对应的URL(SpringBoot使用org.springframework.boot.loader.jar.Handler处理器来处理这些URL):

    jar:file:/Users/Format/Develop/gitrepository/springboot-analysis/springboot-executable-jar/target/executable-jar-1.0-SNAPSHOT.jar!/lib/spring-boot-starter-web-1.3.5.RELEASE.jar!/jar:file:/Users/Format/Develop/gitrepository/springboot-analysis/springboot-executable-jar/target/executable-jar-1.0-SNAPSHOT.jar!/lib/spring-boot-loader-1.3.5.RELEASE.jar!/org/springframework/boot/loader/JarLauncher. class

    # JarLauncher的执行过程

    JarLauncher的main方法:

    publicstaticvoidmain(String[] args) { // 构造JarLauncher,然后调用它的launch方法。参数是控制台传递的new JarLauncher().launch(args);}

    JarLauncher被构造的时候会调用父类ExecutableArchiveLauncher的构造方法。

    ExecutableArchiveLauncher的构造方法内部会去构造Archive,这里构造了JarFileArchive。构造JarFileArchive的过程中还会构造很多东西,比如JarFile,Entry …

    JarLauncher的launch方法:protectedvoid launch(String[] args) {try {// 在系统属性中设置注册了自定义的URL处理器:org.springframework.boot.loader.jar.Handler。如果URL中没有指定处理器,会去系统属性中查询 JarFile.registerUrlProtocolHandler();// get classPathArchives方法在会去找lib目录下对应的第三方依赖JarFileArchive,同时也会项目自身的JarFileArchive// 根据get classPathArchives得到的JarFileArchive集合去创建类加载器 classLoader。这里会构造一个LaunchedURL classLoader类加载器,这个类加载器继承URL classLoader,并使用这些JarFileArchive集合的URL构造成URL classPath// LaunchedURL classLoader类加载器的父类加载器是当前执行类JarLauncher的类加载器 classLoader classLoader = create classLoader(get classPathArchives());// getMain class方法会去项目自身的Archive中的Manifest中找出key为Start- class的类// 调用重载方法launch launch(args, getMain class(), classLoader); }catch (Exception ex) { ex.printStackTrace(); System.exit(1); }}// Archive的getMain class方法// 这里会找出spring.study.executablejar.ExecutableJarApplication这个类publicString getMain class() throws Exception { Manifest manifest = getManifest();String main class = null;if (manifest != null) { main class = manifest.getMainAttributes().getValue("Start- class"); }if (main class == null) {thrownew IllegalStateException("No 'Start- class' manifest entry specified in " + this); }return main class;}// launch重载方法protectedvoid launch(String[] args, String main class, classLoader classLoader) throws Exception {// 创建一个MainMethodRunner,并把args和Start- class传递给它 Runnable runner = createMainMethodRunner(main class, args, classLoader);// 构造新线程 Thread runnerThread = new Thread(runner);// 线程设置类加载器以及名字,然后启动 runnerThread.setContext classLoader( classLoader); runnerThread.setName(Thread.currentThread().getName()); runnerThread.start();}

    MainMethodRunner的run方法:

    @Overridepublicvoid run() {try {// 根据Start- class进行实例化 class<?> main class = Thread.currentThread().getContext classLoader() .load class(this.main className);// 找出main方法 Method mainMethod = main class.getDeclaredMethod("main", String[]. class);// 如果main方法不存在,抛出异常if (mainMethod == null) {thrownew IllegalStateException(this.main className + " does not have a main method"); }// 调用 mainMethod.invoke(null, newObject[] { this.args }); }catch (Exception ex) { UncaughtExceptionHandler handler = Thread.currentThread() .getUncaughtExceptionHandler();if (handler != null) { handler.uncaughtException(Thread.currentThread(), ex); }thrownew RuntimeException(ex); }}

    # 关于自定义的类加载器LaunchedURL classLoader

    LaunchedURL classLoader重写了load class方法,也就是说它修改了默认的类加载方式(先看该类是否已加载这部分不变,后面真正去加载类的规则改变了,不再是直接从父类加载器中去加载)。LaunchedURL classLoader定义了自己的类加载规则:

    private class<?> doLoad class(String name) throws classNotFoundException {// 1) Try the root class loadertry {if (this.root classLoader != null) {returnthis.root classLoader.load class(name); } }catch (Exception ex) {// Ignore and continue }// 2) Try to find locallytry { findPackage(name); class<?> cls = find class(name);return cls; }catch (Exception ex) {// Ignore and continue }// 3) Use standard loadingreturnsuper.load class(name, false);}

    加载规则:

  • 调用LaunchedURL classLoader自身的find class方法,也就是URL classLoader的find class方法

  • 调用父类的load class方法,也就是执行默认的类加载顺序(从Bootstrap classLoader开始从下往下寻找)

  • LaunchedURL classLoader自身的find class方法:

    protected class<?> find class(final String name)throws classNotFoundException{try {return AccessController.doPrivileged(new PrivilegedExceptionAction< class<?>>() {public class<?> run() throws classNotFoundException {// 把类名解析成路径并加上. class后缀 String path = name.replace('.', '/').concat(". class");// 基于之前得到的第三方jar包依赖以及自己的jar包得到URL数组,进行遍历找出对应类名的资源// 比如path是org/springframework/boot/loader/JarLauncher. class,它在jar:file:/Users/Format/Develop/gitrepository/springboot-analysis/springboot-executable-jar/target/executable-jar-1.0-SNAPSHOT.jar!/lib/spring-boot-loader-1.3.5.RELEASE.jar!/中被找出// 那么找出的资源对应的URL为jar:file:/Users/Format/Develop/gitrepository/springboot-analysis/springboot-executable-jar/target/executable-jar-1.0-SNAPSHOT.jar!/lib/spring-boot-loader-1.3.5.RELEASE.jar!/org/springframework/boot/loader/JarLauncher. class Resource res = ucp.getResource(path, false);if (res != null) { // 找到了资源try {return define class(name, res); } catch (IOException e) {thrownew classNotFoundException(name, e); } } else { // 找不到资源的话直接抛出 classNotFoundException异常thrownew classNotFoundException(name); } } }, acc); } catch (java.security.PrivilegedActionException pae) {throw ( classNotFoundException) pae.getException(); }}

    下面是LaunchedURL classLoader的一个测试:

    // 注册org.springframework.boot.loader.jar.Handler URL协议处理器JarFile.registerUrlProtocolHandler();// 构造LaunchedURL classLoader类加载器,这里使用了2个URL,分别对应jar包中依赖包spring-boot-loader和spring-boot,使用 "!/" 分开,需要org.springframework.boot.loader.jar.Handler处理器处理LaunchedURL classLoader classLoader = new LaunchedURL classLoader(new URL[] {new URL("jar:file:/Users/Format/Develop/gitrepository/springboot-analysis/springboot-executable-jar/target/executable-jar-1.0-SNAPSHOT.jar!/lib/spring-boot-loader-1.3.5.RELEASE.jar!/") , new URL("jar:file:/Users/Format/Develop/gitrepository/springboot-analysis/springboot-executable-jar/target/executable-jar-1.0-SNAPSHOT.jar!/lib/spring-boot-1.3.5.RELEASE.jar!/") }, LaunchedURL classLoaderTest. class.get classLoader());// 加载类// 这2个类都会在第二步本地查找中被找出(URL classLoader的find class方法) classLoader.load class("org.springframework.boot.loader.JarLauncher"); classLoader.load class("org.springframework.boot.SpringApplication");// 在第三步使用默认的加载顺序在Application classLoader中被找出 classLoader.load class("org.springframework.boot.autoconfigure.web.DispatcherServletAutoConfiguration");

    # Spring Boot Loader的作用

    org.springframework.boot.loader.jar.Handler处理器处理。它的Main- class使用JarLauncher,如果是war包,使用WarLauncher执行。这些Launcher内部都会另起一个线程启动自定义的SpringApplication类。

    这些特性通过spring-boot-maven-plugin插件打包完成。

    热门推荐