Spring Boot包結構以及啟動過程
阿新 • • 發佈:2018-12-12
通過IDEA 自動構建一個SpringBoot專案,通過maven構建工具進行打包之後,在target目錄下,生成Jar包,使用java -jar target.jar,一個簡單的SpringBoot專案即可啟動完成。
Jar包啟動的邏輯:
Jar包下必有META-INFO/MANIFEST.MF 檔案,這個檔案定義了構建時間,構建人,構建的工具版本,構建的JDK版本等資訊
如:servlet-api.jar下的配置檔案
Manifest-Version: 1.0 Ant-Version: Apache Ant 1.6.5 Created-By: Apache Maven Built-By: edburns Package: Build-Jdk: 1.5.0_06 Extension-Name: servlet-api Specification-Title: A component of the Glassfish Application Server Specification-Vendor: Sun Microsystems Inc Implementation-Title: Implementation-Vendor: Sun Microsystems Inc Implementation-Version: 2.5
一個Jar包啟動的時候,啟動主函式通過配置MANIFEST.MF 中的 Main-Class來決定,springboot專案也不例外
SpringBoot專案的MANIFEST.MF 如下
Manifest-Version: 1.0 Implementation-Title: demo Implementation-Version: 0.0.1-SNAPSHOT Built-By: zhaokui Implementation-Vendor-Id: com.example Spring-Boot-Version: 2.0.5.RELEASE Main-Class: org.springframework.boot.loader.JarLauncher Start-Class: com.example.demo.DemoApplication Spring-Boot-Classes: BOOT-INF/classes/ Spring-Boot-Lib: BOOT-INF/lib/ Created-By: Apache Maven 3.5.4 Build-Jdk: 1.8.0_181 Implementation-URL: https://projects.spring.io/spring-boot/#/spring-bo ot-starter-parent/demo
由此可以看出SpringBoot的啟動類並非我們的 com.example.demo.DemoApplication,而是 org.springframework.boot.loader.JarLauncher。
SpringBoot通過指定我們的執行的Classes路徑和Lib路徑來載入我們的類,然後使用反射invoke我們的主函式來載入進行啟動
所以springBootJar包專案的目錄結構如下
drwxr-xr-x 4 hello staff 128B 9 25 21:26 BOOT-INF drwxr-xr-x 4 hello staff 128B 9 25 21:26 META-INF -rw-r--r-- 1 hello staff 16M 9 25 21:26 demo-0.0.1-SNAPSHOT.jar drwxr-xr-x 3 hello staff 96B 9 25 21:26 org
其中org目錄下JarLaunher的啟動類,BOOT-IFNO裡面包含了專案依賴的jar包以及我們編寫的程式碼
因此 SpringBoot專案 只需要簡單的 java -jar 專案.jar即可,所有的配置MANIFEST.MF,在Maven springboot plugin中自動生成配置
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
後續會帶來Spring配置檔案如何自動載入,以及載入順序和載入邏輯