面試官問(wèn):為什么SpringBoot的 jar 可以直接運(yùn)行?
來(lái)源 | http://fangjian0423.github.io/
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
├── 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
java -jar executable-jar-1.0-SNAPSHOT.jarMETA-INF文件夾:程序入口,其中MANIFEST.MF用于描述jar包的信息 lib目錄:放置第三方依賴的jar包,比如springboot的一些jar包 spring boot loader相關(guān)的代碼 模塊自身的代碼
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
Spring Boot Loader抽象的一些類
jar:file:/Users/format/Develop/gitrepository/springboot-analysis/springboot-executable-jar/target/executable-jar-1.0-SNAPSHOT.jar!/
/Users/format/Develop/gitrepository/springboot-analysis/springboot-executable-jar/target/executable-jar-1.0-SNAPSHOT.jar
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
...
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的執(zhí)行過(guò)程
public static void main(String[] args) {
// 構(gòu)造JarLauncher,然后調(diào)用它的launch方法。參數(shù)是控制臺(tái)傳遞的
new JarLauncher().launch(args);
}
JarLauncher的launch方法:
protected void launch(String[] args) {
try {
// 在系統(tǒng)屬性中設(shè)置注冊(cè)了自定義的URL處理器:org.springframework.boot.loader.jar.Handler。如果URL中沒有指定處理器,會(huì)去系統(tǒng)屬性中查詢
JarFile.registerUrlProtocolHandler();
// getClassPathArchives方法在會(huì)去找lib目錄下對(duì)應(yīng)的第三方依賴JarFileArchive,同時(shí)也會(huì)項(xiàng)目自身的JarFileArchive
// 根據(jù)getClassPathArchives得到的JarFileArchive集合去創(chuàng)建類加載器ClassLoader。這里會(huì)構(gòu)造一個(gè)LaunchedURLClassLoader類加載器,這個(gè)類加載器繼承URLClassLoader,并使用這些JarFileArchive集合的URL構(gòu)造成URLClassPath
// LaunchedURLClassLoader類加載器的父類加載器是當(dāng)前執(zhí)行類JarLauncher的類加載器
ClassLoader classLoader = createClassLoader(getClassPathArchives());
// getMainClass方法會(huì)去項(xiàng)目自身的Archive中的Manifest中找出key為Start-Class的類
// 調(diào)用重載方法launch
launch(args, getMainClass(), classLoader);
}
catch (Exception ex) {
ex.printStackTrace();
System.exit(1);
}
}
// Archive的getMainClass方法
// 這里會(huì)找出spring.study.executablejar.ExecutableJarApplication這個(gè)類
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 {
// 創(chuàng)建一個(gè)MainMethodRunner,并把a(bǔ)rgs和Start-Class傳遞給它
Runnable runner = createMainMethodRunner(mainClass, args, classLoader);
// 構(gòu)造新線程
Thread runnerThread = new Thread(runner);
// 線程設(shè)置類加載器以及名字,然后啟動(dòng)
runnerThread.setContextClassLoader(classLoader);
runnerThread.setName(Thread.currentThread().getName());
runnerThread.start();
}
@Override
public void run() {
try {
// 根據(jù)Start-Class進(jìn)行實(shí)例化
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");
}
// 調(diào)用
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);
}
}
關(guān)于自定義的類加載器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);
}
如果根類加載器存在,調(diào)用它的加載方法。這里是根類加載是ExtClassLoader 調(diào)用LaunchedURLClassLoader自身的findClass方法,也就是URLClassLoader的findClass方法 調(diào)用父類的loadClass方法,也就是執(zhí)行默認(rèn)的類加載順序(從BootstrapClassLoader開始從下往下尋找)
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");
// 基于之前得到的第三方j(luò)ar包依賴以及自己的jar包得到URL數(shù)組,進(jìn)行遍歷找出對(duì)應(yīng)類名的資源
// 比如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!/中被找出
// 那么找出的資源對(duì)應(yīng)的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();
}
}
// 注冊(cè)org.springframework.boot.loader.jar.Handler URL協(xié)議處理器
JarFile.registerUrlProtocolHandler();
// 構(gòu)造LaunchedURLClassLoader類加載器,這里使用了2個(gè)URL,分別對(duì)應(yīng)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個(gè)類都會(huì)在第二步本地查找中被找出(URLClassLoader的findClass方法)
classLoader.loadClass("org.springframework.boot.loader.JarLauncher");
classLoader.loadClass("org.springframework.boot.SpringApplication");
// 在第三步使用默認(rèn)的加載順序在ApplicationClassLoader中被找出
classLoader.loadClass("org.springframework.boot.autoconfigure.web.DispatcherServletAutoConfiguration");
Spring Boot Loader的作用
往期推薦:
推薦一套超高顏值的 Spring Boot 快速開發(fā)框架【文末送書】
評(píng)論
圖片
表情
