SpringBoot的Jar的運行方式

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

1
2
3
4
5
6
7
8



org.springframework.boot
spring-boot-maven-plugin



打包完生成的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包就能啓動程序了:

1
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方法:

1
2
3
4
public static void main(String[] args) {
// 構造JarLauncher,然後調用它的launch方法。參數是控制檯傳遞的
new JarLauncher().launch(args);
}
JarLauncher被構造的時候會調用父類ExecutableArchiveLauncher的構造方法。

ExecutableArchiveLauncher的構造方法內部會去構造Archive,這裏構造了JarFileArchive。構造JarFileArchive的過程中還會構造很多東西,比如JarFile,Entry …

JarLauncher的launch方法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
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方法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
@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定義了自己的類加載規則:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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方法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
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的一個測試:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// 註冊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插件打包完成。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章