当前位置: 移动技术网 > IT编程>开发语言>Java > 为什么SpringBoot的jar可以直接运行

为什么SpringBoot的jar可以直接运行

2020年05月13日  | 移动技术网IT编程  | 我要评论

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.0
implementation-title: executable-jar
implementation-version: 1.0-snapshot
archiver-version: plexus archiver
built-by: format
start-class: spring.study.executablejar.executablejarapplication
implementation-vendor-id: spring.study
spring-boot-version: 1.3.5.release
created-by: apache maven 3.2.3
build-jdk: 1.8.0_20
implementation-vendor: pivotal software, 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.mf
spring/
spring/study/
....
spring/study/executablejar/executablejarapplication.class
lib/spring-boot-starter-1.3.5.release.jar
lib/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

我们看到如果有jar包中包含jar,或者jar包中包含jar包里面的class文件,那么会使 用 !/ 分隔开,这种方式只有org.springframework.boot.loader.jar.handler能处 理,它是springboot内部扩展出来的一种url协议。

jarlauncher的执行过程

jarlauncher的main方法:

public static void main(string[] args) {
  // 构造jarlauncher,然后调用它的launch方法。参数是控制台传递的
  new jarlauncher().launch(args);
} 

jarlauncher被构造的时候会调用父类executablearchivelauncher的构造方法。

executablearchivelauncher的构造方法内部会去构造archive,这里构造了jarfilearchive。构造jarfilearchive的过程中还会构造很多东西,比如jarfile,entry …

jarlauncher的launch方法:

protected void launch(string[] args) {
 try {
  // 在系统属性中设置注册了自定义的url处理器:org.springframework.boot.loader.jar.handler。如果url中没有指定处理器,会去系统属性中查询
  jarfile.registerurlprotocolhandler();
  // getclasspatharchives方法在会去找lib目录下对应的第三方依赖jarfilearchive,同时也会项目自身的jarfilearchive
  // 根据getclasspatharchives得到的jarfilearchive集合去创建类加载器classloader。这里会构造一个launchedurlclassloader类加载器,这个类加载器继承urlclassloader,并使用这些jarfilearchive集合的url构造成urlclasspath
  // launchedurlclassloader类加载器的父类加载器是当前执行类jarlauncher的类加载器
  classloader classloader = createclassloader(getclasspatharchives());
  // getmainclass方法会去项目自身的archive中的manifest中找出key为start-class的类
  // 调用重载方法launch
  launch(args, getmainclass(), classloader);
 }
 catch (exception ex) {
  ex.printstacktrace();
  system.exit(1);
 }
}
 
// archive的getmainclass方法
// 这里会找出spring.study.executablejar.executablejarapplication这个类
public string getmainclass() throws exception {
 manifest manifest = 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);
 }
 return mainclass;
}
 
// launch重载方法
protected void launch(string[] args, string mainclass, classloader classloader)
  throws exception {
   // 创建一个mainmethodrunner,并把args和start-class传递给它
 runnable runner = createmainmethodrunner(mainclass, args, classloader);
   // 构造新线程
 thread runnerthread = new thread(runner);
   // 线程设置类加载器以及名字,然后启动
 runnerthread.setcontextclassloader(classloader);
 runnerthread.setname(thread.currentthread().getname());
 runnerthread.start();
}

mainmethodrunner的run方法:

@override
public void run() {
 try {
  // 根据start-class进行实例化
  class<?> mainclass = thread.currentthread().getcontextclassloader()
    .loadclass(this.mainclassname);
  // 找出main方法
  method mainmethod = mainclass.getdeclaredmethod("main", string[].class);
  // 如果main方法不存在,抛出异常
  if (mainmethod == null) {
   throw new illegalstateexception(
     this.mainclassname + " does not have a main method");
  }
  // 调用
  mainmethod.invoke(null, new object[] { this.args });
 }
 catch (exception ex) {
  uncaughtexceptionhandler handler = thread.currentthread()
    .getuncaughtexceptionhandler();
  if (handler != null) {
   handler.uncaughtexception(thread.currentthread(), ex);
  }
  throw new runtimeexception(ex);
 }
}

start-class的main方法调用之后,内部会构造spring容器,启动内置servlet容器等过程。这些过程我们都已经分析过了。

关于自定义的类加载器launchedurlclassloader

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

private class<?> doloadclass(string name) throws classnotfoundexception {
 
 // 1) try the root class loader
 try {
  if (this.rootclassloader != null) {
   return this.rootclassloader.loadclass(name);
  }
 }
 catch (exception ex) {
  // ignore and continue
 }
 
 // 2) try to find locally
 try {
  findpackage(name);
  class<?> cls = findclass(name);
  return cls;
 }
 catch (exception ex) {
  // ignore and continue
 }
 
 // 3) use standard loading
 return super.loadclass(name, false);
}

加载规则:

  • 如果根类加载器存在,调用它的加载方法。这里是根类加载是extclassloader
  • 调用launchedurlclassloader自身的findclass方法,也就是urlclassloader的findclass方法
  • 调用父类的loadclass方法,也就是执行默认的类加载顺序(从bootstrapclassloader开始从下往下寻找)

launchedurlclassloader自身的findclass方法:

protected class<?> findclass(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 defineclass(name, res);
            } catch (ioexception e) {
              throw new classnotfoundexception(name, e);
            }
          } else { // 找不到资源的话直接抛出classnotfoundexception异常
            throw new classnotfoundexception(name);
          }
        }
      }, acc);
  } catch (java.security.privilegedactionexception pae) {
    throw (classnotfoundexception) pae.getexception();
  }
}

下面是launchedurlclassloader的一个测试:

// 注册org.springframework.boot.loader.jar.handler url协议处理器
jarfile.registerurlprotocolhandler();
// 构造launchedurlclassloader类加载器,这里使用了2个url,分别对应jar包中依赖包spring-boot-loader和spring-boot,使用 "!/" 分开,需要org.springframework.boot.loader.jar.handler处理器处理
launchedurlclassloader classloader = new launchedurlclassloader(
    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!/")
    },
    launchedurlclassloadertest.class.getclassloader());
 
// 加载类
// 这2个类都会在第二步本地查找中被找出(urlclassloader的findclass方法)
classloader.loadclass("org.springframework.boot.loader.jarlauncher");
classloader.loadclass("org.springframework.boot.springapplication");
// 在第三步使用默认的加载顺序在applicationclassloader中被找出
classloader.loadclass("org.springframework.boot.autoconfigure.web.dispatcherservletautoconfiguration");

spring boot loader的作用

springboot在可执行jar包中定义了自己的一套规则,比如第三方依赖jar包在/lib目录下,jar包的url路径使用自定义的规则并且这个规则需要使用org.springframework.boot.loader.jar.handler处理器处理。它的main-class使用jarlauncher,如果是war包,使用warlauncher执行。这些launcher内部都会另起一个线程启动自定义的springapplication类。

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

到此这篇关于为什么springboot的jar可以直接运行 的文章就介绍到这了,更多相关springboot jar运行内容请搜索移动技术网以前的文章或继续浏览下面的相关文章希望大家以后多多支持移动技术网! 

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网