https://github.com/zq2599/blog_demoshtml
内容:全部原创文章分类汇总及配套源码,涉及Java、Docker、Kubernetes、DevOPS等;java
https://github.com/zq2599/blog_demos
内容:全部原创文章分类汇总及配套源码,涉及Java、Docker、Kubernetes、DevOPS等;git
在开发springboot应用时,经过java -jar命令启动应用是经常使用的方式,今天就来一块儿了解这个简单操做背后的技术;程序员
开发一个springboot应用做为本次研究的对象,对应的版本信息以下:github
接下来开发springboot应用,这个应用很是简单:web
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.3.1.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.bolingcavalry</groupId> <artifactId>springbootstarterdemo</artifactId> <version>0.0.1-SNAPSHOT</version> <name>springbootstarterdemo</name> <description>Demo project for Spring Boot</description> <properties> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
package com.bolingcavalry.springbootstarterdemo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.Date; @SpringBootApplication @RestController public class SpringbootstarterdemoApplication { public static void main(String[] args) { SpringApplication.run(SpringbootstarterdemoApplication.class, args); } @RequestMapping(value = "/hello") public String hello(){ return "hello " + new Date(); } }
mvn clean package -U -DskipTests
先要弄清楚java -jar命令作了什么,在oracle官网找到了该命令的描述:
If the -jar option is specified, its argument is the name of the JAR file containing class and resource files for the application. The startup class must be indicated by the Main-Class manifest header in its source code.
spring
再次秀出我蹩脚的英文翻译:docker
小结一下:
java -jar会去找jar中的manifest文件,在那里面找到真正的启动类;shell
Spring-Boot-Classpath-Index: BOOT-INF/classpath.idx Implementation-Title: springbootstarterdemo Implementation-Version: 0.0.1-SNAPSHOT Start-Class: com.bolingcavalry.springbootstarterdemo.Springbootstarter demoApplication Spring-Boot-Classes: BOOT-INF/classes/ Spring-Boot-Lib: BOOT-INF/lib/ Build-Jdk-Spec: 1.8 Spring-Boot-Version: 2.3.1.RELEASE Created-By: Maven Jar Plugin 3.2.0 Implementation-Vendor: Pivotal Software, Inc. Main-Class: org.springframework.boot.loader.JarLauncher
Start-Class: com.bolingcavalry.springbootstarterdemo.Springbootstarter demoApplication
动手以前先猜一下,我的以为缘由应该以下:数据库
3. java -jar执行的是JarLauncher的main方法,以下,会实例化一个JarLauncher对象,而后执行其launch方法,而且将全部入参都带入:
public static void main(String[] args) throws Exception { new JarLauncher().launch(args); }
protected void launch(String[] args) throws Exception { // 将jar解压后运行的方式叫作exploded mode // 若是是exploded mode,就不能支持经过URL加载jar // 若是不是exploded mode,就能够经过URL加载jar if (!isExploded()) { // 若是容许经过URL加载jar,就在此注册对应的处理类 JarFile.registerUrlProtocolHandler(); } // 建立classLoader ClassLoader classLoader = createClassLoader(getClassPathArchivesIterator()); // jarmode是建立docker镜像时用到的参数,使用该参数是为了生成带有多个layer信息的镜像 // 这里暂时不关注jarmode String jarMode = System.getProperty("jarmode"); //若是没有jarmode参数,launchClass的值就来自getMainClass()返回 String launchClass = (jarMode != null && !jarMode.isEmpty()) ? JAR_MODE_LAUNCHER : getMainClass(); launch(args, launchClass, classLoader); }
public ExecutableArchiveLauncher() { try { this.archive = createArchive(); this.classPathIndex = getClassPathIndex(this.archive); } catch (Exception ex) { throw new IllegalStateException(ex); } }
protected final Archive createArchive() throws Exception { ProtectionDomain protectionDomain = 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"); } File root = new File(path); if (!root.exists()) { throw new IllegalStateException("Unable to determine code source archive from " + root); } return (root.isDirectory() ? new ExplodedArchive(root) : new JarFileArchive(root)); }
@Override protected String getMainClass() throws Exception { // 对应的是JarFileArchive.getManifest方法, // 进去后发现对应的就是JarFile.getManifest方法, // JarFile.getManifest对应的就是META-INF/MANIFEST.MF文件的内容 Manifest manifest = this.archive.getManifest(); String mainClass = null; if (manifest != null) { // 对应的是META-INF/MANIFEST.MF文件中的Start-Class的属性 mainClass = manifest.getMainAttributes().getValue(START_CLASS_ATTRIBUTE); } if (mainClass == null) { throw new IllegalStateException("No 'Start-Class' manifest entry specified in " + this); } return mainClass; }
protected void launch(String[] args) throws Exception { if (!isExploded()) { JarFile.registerUrlProtocolHandler(); } ClassLoader classLoader = createClassLoader(getClassPathArchivesIterator()); String jarMode = System.getProperty("jarmode"); // 这里的launchClass等于"com.bolingcavalry.springbootstarterdemo.SpringbootstarterdemoApplication" String launchClass = (jarMode != null && !jarMode.isEmpty()) ? JAR_MODE_LAUNCHER : getMainClass(); // 这里就是启动SpringbootstarterdemoApplication的地方 launch(args, launchClass, classLoader); }
public class MainMethodRunner { private final String mainClassName; private final String[] args; /** * Create a new {@link MainMethodRunner} instance. * @param mainClass the main class * @param args incoming arguments */ public MainMethodRunner(String mainClass, String[] args) { // mainClassName被赋值为"com.bolingcavalry.springbootstarterdemo.SpringbootstarterdemoApplication" this.mainClassName = mainClass; this.args = (args != null) ? args.clone() : null; } public void run() throws Exception { // 获得SpringbootstarterdemoApplication的Class对象 Class<?> mainClass = Class.forName(this.mainClassName, false, Thread.currentThread().getContextClassLoader()); // 获得SpringbootstarterdemoApplication的main方法对象 Method mainMethod = mainClass.getDeclaredMethod("main", String[].class); mainMethod.setAccessible(true); // 经过反射执行main方法 mainMethod.invoke(null, new Object[] { this.args }); } }
终于,真相大白了;
最后尽量简短作个小结,先看jar是如何产生的,以下图,maven插件生成的jar文件中,有常见的class、jar,也有符合java规范的MANIFEST.MF文件,而且,还在MANIFEST.MF文件中额外生成了名为Start-Class的配置,这里面是咱们编写的应用启动类SpringbootstarterdemoApplication:
启动类是JarLauncher,它是如何与MANIFEST.MF文件关联的呢?从下图能够看出,最终是经过JarFile类的成员变量manifestSupplier关联上的:
再来看看关键代码的执行状况,以下图:
至此,SpringBoot的jar独立运行的基本原理已经清楚,探究的过程当中,除了熟悉关键代码流程,还对jar中的文件有了更多了解,若是您正在学习SpringBoot,但愿本文能给您一些参考;
微信搜索「程序员欣宸」,我是欣宸,期待与您一同畅游Java世界...
https://github.com/zq2599/blog_demos