亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

SpringBoot啟動流程入口參數(shù)創(chuàng)建對象源碼分析

 更新時間:2023年04月03日 11:50:34   作者:唐小碼  
這篇文章主要為大家介紹了SpringBoot啟動流程入口參數(shù)研究及創(chuàng)建對象源碼分析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪

入口

這不最近到金三銀四的季節(jié)了么,有個朋友去參加了一個面試,回來的時候給我說其它還可以,但是問到SpringBoot的啟動原理了,說了解的不深,我仔細轉(zhuǎn)過頭來也想了一下自己用了這么長時間的SpringBoot,說實話還真沒有仔細研究過他的啟動原理。我覺得還是有必要去研究一下。

版本: 2.1.8.RELEASE

于是乎,我便打算從他的啟動類上追下源碼,仔細去尋找一下答案。

啟動代碼:

@SpringBootApplcation
public static void main(String[] args) {
    SpringApplication.run(BlogAdminApplication.class, args);
    System.out.println("======== admin start success... ==========");
}

這里傳入了兩個參數(shù),BlogAdminApplication當前類和args參數(shù)

我們點擊進入run方法查看

public static ConfigurableApplicationContext run(Class<?> primarySource, String... args) {
    return run(new Class[]{primarySource}, args);
}

這里是將我們寫的啟動類傳入到了Class[]數(shù)組中,這步就是個單純的參數(shù)轉(zhuǎn)換。

探討primarySource參數(shù)

那么問題是primarySource能接受的類型是啥樣的,是不是什么類都可以接受,帶著這個疑問,我們做一個測試,把這個參數(shù)給換成一個別的類呢,ManagerController類是一個我寫的接口類

@SpringBootApplication
public class BlogProjectApplication {
   public static void main(String[] args) {
       SpringApplication.run(ManagerController.class, args);
       System.out.println("======== admin start success... ==========");
   }
}

控制臺打印

org.springframework.context.ApplicationContextException: Unable to start web server; nested exception is org.springframework.context.ApplicationContextException: Unable to start ServletWebServerApplicationContext due to missing ServletWebServerFactory bean.

提示不能啟動服務,提示缺少了ServletWebServerFactory bean 點進這個類看下

@FunctionalInterface
public interface ServletWebServerFactory {
    WebServer getWebServer(ServletContextInitializer... initializers);
}

他被FunctionalInterface標注了,是一個函數(shù)式接口,只有一個getWebServer方法,用來獲取webServer的 看下他的實現(xiàn)類,

這不就是提示我們?nèi)鄙賳拥姆杖萜髅?,說的直白點,我的理解就是他缺少可以運行的容器,我們知道,沒有使用springboot項目之前,我們的項目都是跑在tomcat容器上的,當然也有使用Jetty容器的。再者,我們知道SpringBoot是對tomcat進行了內(nèi)置。而SpringBoot不僅僅是只有內(nèi)置了tomcat,而且還內(nèi)置了好多的東西,比如我們經(jīng)常使用的mq、redis等等一系列的東西,這個我們可以在spring.factories配置文件中看到,這個文件位于如下位置

大概內(nèi)容有下,篇幅有限,就不一一列舉了。

省略。。。
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
org.springframework.boot.autoconfigure.admin.SpringApplicationAdminJmxAutoConfiguration,\
org.springframework.boot.autoconfigure.aop.AopAutoConfiguration,\
org.springframework.boot.autoconfigure.amqp.RabbitAutoConfiguration,\
org.springframework.boot.autoconfigure.batch.BatchAutoConfiguration,\
org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration,\
省略。。。

那么回過頭來,我們再看下這個問題,這些個類是如何被加載進來的,我們知道SpingBoot有個注解是開啟自動注解的@EnableAutoConfiguration,他就干這個事情的。他能夠激活SpringBoot內(nèi)建和自定義組件的自動裝配特性。

那么,知道了這些,我們把這個之前修改后的類給改造一下,加上注解@EnableAutoConfiguration,看下執(zhí)行效果。

@RestController
@RequestMapping("project/manager")
@EnableAutoConfiguration
public class ManagerController extends AbstractController {

運行如下

從打印信息就能知道,服務器有了,只不過下面報錯,提示找不到bean,那這不就簡單了么,他是不是就是沒有掃描到我們的包么,這里就其實可以在配置掃描包的注解繼續(xù)測試,我就懶的不測試了,直接去看@SpringBootApplication注解

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration
//
@ComponentScan(
    excludeFilters = {@Filter(
    type = FilterType.CUSTOM,
    classes = {TypeExcludeFilter.class}
), @Filter(
    type = FilterType.CUSTOM,
    classes = {AutoConfigurationExcludeFilter.class}
)}
)
public @interface SpringBootApplication {

@SpringBootApplication這個注解其實就是一個組合注解,里面包含了

  • 元注解:用來標注他是一個注解的,jdk自帶的
  • @SpringBootConfiguration:集成自@Configuration,表示是一個配置類
  • @EnableAutoConfiguration:激活SpringBoot內(nèi)建和自定義組件的自動裝配特性
  • @ComponentScan:掃描注解,添加了排除參數(shù),指定排除了一些類

通過這里的實驗,我們可以得出結(jié)論:

primarySource參數(shù)能接收的類是一個配置類,同時要把符合掃描規(guī)則的類裝配到spring容器中,并且對SpringBoot內(nèi)置的一些類進行自動掃描到,而這里的@SpringBootApplication注解就是把這些特性都整合到了一起,作為了一個引導類而已。那么說白了,primarySource他接受的其實就是一個配置類。

關(guān)于注解詳細知識的話,這里就聊這么多了,后面再詳細聊。

args參數(shù)

args是Java命令行參數(shù),我們在DOS中執(zhí)行Java程序的時候使用“java 文件名 args參數(shù)”。args這個數(shù)組可以接收到這些參數(shù)。這個是個基礎常識了。

以下我們將繼續(xù)跟蹤源碼進行分析

我們繼續(xù)追run()方法

public static ConfigurableApplicationContext run(Class&lt;?&gt;[] primarySources, String[] args) {
    return (new SpringApplication(primarySources)).run(args);
}

這個方法干了兩個事情:

1、new SpringApplication()來創(chuàng)建對象

2、通過創(chuàng)建后的對象,調(diào)用對象里面的run()方法

以下我們將從這兩個地方進行分析,本篇就先研究第一個

創(chuàng)建對象

我們先看下他是怎么創(chuàng)建對象的,創(chuàng)建了哪些對象,

public SpringApplication(Class<?>... primarySources) {
    this((ResourceLoader)null, primarySources);
}
public SpringApplication(ResourceLoader resourceLoader, Class<?>... primarySources) {
    //資源加載器
   this.resourceLoader = resourceLoader;
   //斷言
   Assert.notNull(primarySources, "PrimarySources must not be null");
   //對primarySources進行存儲到LinkedHashSet
   this.primarySources = new LinkedHashSet<>(Arrays.asList(primarySources));
   //1、推斷web應用類別
   this.webApplicationType = WebApplicationType.deduceFromClasspath();
   //2、加載Spring應用上下文初始化
   setInitializers((Collection) getSpringFactoriesInstances(ApplicationContextInitializer.class));
   //3、加載Spring應用事件監(jiān)聽器
   setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class));
   //4、推斷應用引導類
   this.mainApplicationClass = deduceMainApplicationClass();
}

下面研究下主要流程部分

1、推斷web應用類別

推斷web應用類型屬于SpringBoot應用web類型的初始化過程。而該類型也可在SpringApplication構(gòu)造后,run方法執(zhí)行之前,通過setWebApplicationType(WebApplicationType webApplicationType)方法進行調(diào)整。

在推斷Web應用類型的過程中,由于當前Spring應用上下文尚未準備(可在代碼執(zhí)行順序中看到),所以實現(xiàn)采用的是檢查檢查當前ClassLoader下基準Class的存在性判斷。

上源碼

this.webApplicationType = WebApplicationType.deduceFromClasspath();
private static final String[] SERVLET_INDICATOR_CLASSES = { "javax.servlet.Servlet",
      "org.springframework.web.context.ConfigurableWebApplicationContext" };
private static final String WEBMVC_INDICATOR_CLASS = "org.springframework." + "web.servlet.DispatcherServlet";
private static final String WEBFLUX_INDICATOR_CLASS = "org." + "springframework.web.reactive.DispatcherHandler";
private static final String JERSEY_INDICATOR_CLASS = "org.glassfish.jersey.servlet.ServletContainer";
private static final String SERVLET_APPLICATION_CONTEXT_CLASS = "org.springframework.web.context.WebApplicationContext";
private static final String REACTIVE_APPLICATION_CONTEXT_CLASS = "org.springframework.boot.web.reactive.context.ReactiveWebApplicationContext";
static WebApplicationType deduceFromClasspath() {
//當DispatcherHandler存在,且DispatcherServlet、ServletContainer兩個不存在時;換言之,SpringBoot僅依賴WebFlux存在時,此時的應用類型為REACTIVE
   if (ClassUtils.isPresent(WEBFLUX_INDICATOR_CLASS, null) && !ClassUtils.isPresent(WEBMVC_INDICATOR_CLASS, null)
         && !ClassUtils.isPresent(JERSEY_INDICATOR_CLASS, null)) {
      return WebApplicationType.REACTIVE;
   }
   //當Servlet和ConfigurableWebApplicationContext均不存在時,當前應用為非Web應用,即WebApplicationType.NONE,因為這些API均是Spring Web MVC必須的依賴
   for (String className : SERVLET_INDICATOR_CLASSES) {
      if (!ClassUtils.isPresent(className, null)) {
         return WebApplicationType.NONE;
      }
   }
   //當WebFlux和Spring Web MVC同時存在時,Web應用類型同樣是Servlet Web,即WebApplicationType.SERVLET
   return WebApplicationType.SERVLET;
}

2、加載Spring應用上下文初始化

setInitializers((Collection) getSpringFactoriesInstances(ApplicationContextInitializer.class));

此過程包含兩個動作,依次為getSpringFactoriesInstances(ApplicationContextInitializer.class)和setInitializers方法。 先看第一個過程

private <T> Collection<T> getSpringFactoriesInstances(Class<T> type) {
   return getSpringFactoriesInstances(type, new Class<?>[] {});
}
private <T> Collection<T> getSpringFactoriesInstances(Class<T> type, Class<?>[] parameterTypes, Object... args) {
   //獲取類加載器
   ClassLoader classLoader = getClassLoader();
   // Use names and ensure unique to protect against duplicates
   //加載了META-INF/spring.factories資源中配置的ApplicationContextInitializer實現(xiàn)類名單。
   Set<String> names = new LinkedHashSet<>(SpringFactoriesLoader.loadFactoryNames(type, classLoader));
   //初始化
   List<T> instances = createSpringFactoriesInstances(type, parameterTypes, classLoader, args, names);
   AnnotationAwareOrderComparator.sort(instances);
   return instances;
}

此處使用了Spring工廠加載機制方法SpringFactoriesLoader.loadFactoryNames(type, classLoader)。加載了META-INF/spring.factories資源中配置的ApplicationContextInitializer實現(xiàn)類名單。

加載完成后使用createSpringFactoriesInstances方法對其進行初始化。

private <T> List<T> createSpringFactoriesInstances(Class<T> type, Class<?>[] parameterTypes,
      ClassLoader classLoader, Object[] args, Set<String> names) {
   List<T> instances = new ArrayList<>(names.size());
   for (String name : names) {
      try {
      //從類加載器中獲取指定類
         Class<?> instanceClass = ClassUtils.forName(name, classLoader);
         //判斷instanceClass是不是type的子類
         Assert.isAssignable(type, instanceClass);
         //根據(jù)以上獲取的類名創(chuàng)建類的實例
         Constructor<?> constructor = instanceClass.getDeclaredConstructor(parameterTypes);
         //排序
         T instance = (T) BeanUtils.instantiateClass(constructor, args);
         instances.add(instance);
      }
      catch (Throwable ex) {
         throw new IllegalArgumentException("Cannot instantiate " + type + " : " + name, ex);
      }
   }
   return instances;
}

3、加載Spring應用事件監(jiān)聽器

setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class));

此過程與2、加載上下文初始化基本類似。 只不過初始化的對象類型變成了ApplicationListener.class,setListeners方法也只是賦值而已

public void setListeners(Collection<? extends ApplicationListener<?>> listeners) {
   this.listeners = new ArrayList<>();
   this.listeners.addAll(listeners);
}

4、推斷應用引導類

this.mainApplicationClass = deduceMainApplicationClass(); 
private Class<?> deduceMainApplicationClass() {
  try {
     StackTraceElement[] stackTrace = new RuntimeException().getStackTrace();
     for (StackTraceElement stackTraceElement : stackTrace) {
        if ("main".equals(stackTraceElement.getMethodName())) {
           return Class.forName(stackTraceElement.getClassName());
        }
     }
  }
  catch (ClassNotFoundException ex) {
     // Swallow and continue
  }
  return null;
}

這里使用到了new RuntimeException().getStackTrace()來獲取堆棧信息,找到調(diào)用執(zhí)行的main方法,從而確定他的類。
這里有個疑問:他不是傳了primarySources數(shù)組,里面包含了類名么,怎么還用堆棧的方式去獲取,此外,這里的堆棧獲取也只能獲取一個調(diào)用的主main方法,他為啥還要傳一個Class數(shù)組呢?

具體咋獲取的,可以追下源碼,一直跟蹤他的父類Throwable,找到如下代碼

/**
 * Fills in the execution stack trace. This method records within this
 * {@code Throwable} object information about the current state of
 * the stack frames for the current thread.
 *
 * <p>If the stack trace of this {@code Throwable} {@linkplain
 * Throwable#Throwable(String, Throwable, boolean, boolean) is not
 * writable}, calling this method has no effect.
 *
 * @return  a reference to this {@code Throwable} instance.
 * @see     java.lang.Throwable#printStackTrace()
 */
public synchronized Throwable fillInStackTrace() {
    if (stackTrace != null ||
        backtrace != null /* Out of protocol state */ ) {
        fillInStackTrace(0);
        stackTrace = UNASSIGNED_STACK;
    }
    return this;
}
private native Throwable fillInStackTrace(int dummy);

這里最后調(diào)用了native本地方法,去爬取線程堆棧信息,為運行時棧做一份快照。

通過這個圖片,可以看到整個方法的調(diào)用鏈,從下往上看哦

本文僅為個人能力范圍內(nèi)理解,旨在分享出來和大家討論技術(shù),共同努力,共同進步!

參考:《SpringBoot編程思想》

以上就是SpringBoot啟動流程入口參數(shù)創(chuàng)建對象源碼分析的詳細內(nèi)容,更多關(guān)于SpringBoot 啟動參數(shù)創(chuàng)建的資料請關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • Vue中computed計算屬性和data數(shù)據(jù)獲取方式

    Vue中computed計算屬性和data數(shù)據(jù)獲取方式

    這篇文章主要介紹了Vue中computed計算屬性和data數(shù)據(jù)獲取方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-03-03
  • Java適配器模式定義與用法示例

    Java適配器模式定義與用法示例

    這篇文章主要介紹了Java適配器模式定義與用法,結(jié)合具體實例形式分析了java適配器模式的功能、組成、定義、使用方法及適配程度等,需要的朋友可以參考下
    2017-06-06
  • Java如何獲取當前年份、月份和日期字符串

    Java如何獲取當前年份、月份和日期字符串

    Java獲取當前年份、月份和日期是通過Calendar類的實例對象來獲取的,本文通過實例代碼給大家介紹的非常詳細,感興趣的朋友跟隨小編一起看看吧
    2024-03-03
  • 解決spring中redistemplate不能用通配符keys查出相應Key的問題

    解決spring中redistemplate不能用通配符keys查出相應Key的問題

    這篇文章主要介紹了解決spring中redistemplate不能用通配符keys查出相應Key的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-11-11
  • SpringBoot整合Druid實現(xiàn)SQL監(jiān)控和數(shù)據(jù)庫密碼加密

    SpringBoot整合Druid實現(xiàn)SQL監(jiān)控和數(shù)據(jù)庫密碼加密

    Druid連接池是阿里巴巴開源的數(shù)據(jù)庫連接池項目,Druid連接池為監(jiān)控而生,內(nèi)置強大的監(jiān)控功能,監(jiān)控特性不影響性能,本文給大家介紹了SpringBoot整合Druid實現(xiàn)SQL監(jiān)控和數(shù)據(jù)庫密碼加密,文中有相關(guān)的代碼示例供大家參考,需要的朋友可以參考下
    2024-06-06
  • mybatis3中@SelectProvider傳遞參數(shù)方式

    mybatis3中@SelectProvider傳遞參數(shù)方式

    這篇文章主要介紹了mybatis3中@SelectProvider傳遞參數(shù)方式。具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-08-08
  • 詳解Springboot 注入裝配到IOC容器方式

    詳解Springboot 注入裝配到IOC容器方式

    今天通過實例代碼給大家介紹了Springboot 注入裝配到IOC容器方式,代碼簡單易懂,對大家的學習或工作具有一定的參考借鑒價值,感興趣的朋友跟隨小編一起看看吧
    2021-10-10
  • springboot中使用redis的方法代碼詳解

    springboot中使用redis的方法代碼詳解

    &#8203;redis 作為一個高性能的內(nèi)存數(shù)據(jù)庫,如果不會用就太落伍了,之前在 node.js 中用過 redis,本篇記錄如何將 redis 集成到 spring boot 中。感興趣的朋友跟隨小編一起看看吧
    2019-05-05
  • 使用java獲取md5值的兩種方法

    使用java獲取md5值的兩種方法

    本篇文章是對使用java獲取md5值的兩種方法進行了詳細的分析介紹,需要的朋友參考下
    2013-06-06
  • 如何通過javacv實現(xiàn)圖片去水?。ǜ酱a)

    如何通過javacv實現(xiàn)圖片去水印(附代碼)

    這篇文章主要介紹了如何通過javacv實現(xiàn)圖片去水?。ǜ酱a),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
    2019-07-07

最新評論