springboot工作原理


SpringBoot為我們做的自動配置,確實方便快捷,但一直搞不明白它的內部啟動原理,這次就來一步步解開SpringBoot的神秘面紗,讓它不再神秘。

  1.  
    @SpringBootApplication
  2.  
    public class Application {
  3.  
    public static void main(String[] args) {
  4.  
    SpringApplication.run(Application.class, args);
  5.  
    }
  6.  
    }

從上面代碼可以看出,Annotation定義(@SpringBootApplication)和類定義(SpringApplication.run)最為耀眼,所以要揭開SpringBoot的神秘面紗,我們要從這兩位開始就可以了。

SpringBootApplication背后的秘密

  1.  
    @Target(ElementType.TYPE) // 注解的適用范圍,其中TYPE用於描述類、接口(包括包注解類型)或enum聲明
  2.  
    @Retention(RetentionPolicy.RUNTIME) // 注解的生命周期,保留到class文件中(三個生命周期)
  3.  
    @Documented // 表明這個注解應該被javadoc記錄
  4.  
    @Inherited // 子類可以繼承該注解
  5.  
    @SpringBootConfiguration // 繼承了Configuration,表示當前是注解類
  6.  
    @EnableAutoConfiguration // 開啟springboot的注解功能,springboot的四大神器之一,其借助@import的幫助
  7.  
    @ComponentScan(excludeFilters = { // 掃描路徑設置(具體使用待確認)
  8.  
    @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
  9.  
    @Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
  10.  
    public @interface SpringBootApplication {
  11.  
    ...
  12.  
    }

雖然定義使用了多個Annotation進行了原信息標注,但實際上重要的只有三個Annotation:

@Configuration(@SpringBootConfiguration點開查看發現里面還是應用了@Configuration)
@EnableAutoConfiguration
@ComponentScan
所以,如果我們使用如下的SpringBoot啟動類,整個SpringBoot應用依然可以與之前的啟動類功能對等:

  1.  
    @Configuration
  2.  
    @EnableAutoConfiguration
  3.  
    @ComponentScan
  4.  
    public class Application {
  5.  
    public static void main(String[] args) {
  6.  
    SpringApplication.run(Application.class, args);
  7.  
    }
  8.  
    }

每次寫這3個比較累,所以寫一個@SpringBootApplication方便點。接下來分別介紹這3個Annotation。

@Configuration

這里的@Configuration對我們來說不陌生,它就是JavaConfig形式的Spring Ioc容器的配置類使用的那個@Configuration,SpringBoot社區推薦使用基於JavaConfig的配置形式,所以,這里的啟動類標注了@Configuration之后,本身其實也是一個IoC容器的配置類。
舉幾個簡單例子回顧下,XML跟config配置方式的區別:

表達形式層面
基於XML配置的方式是這樣:

  1.  
    <?xml version="1.0" encoding="UTF-8"?>
  2.  
    <beans xmlns="http://www.springframework.org/schema/beans"
  3.  
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4.  
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"
  5.  
    default-lazy-init="true">
  6.  
    <!--bean定義-->
  7.  
    </beans>

而基於JavaConfig的配置方式是這樣:

  1.  
    @Configuration
  2.  
    public class MockConfiguration{
  3.  
    //bean定義
  4.  
    }

任何一個標注了@Configuration的Java類定義都是一個JavaConfig配置類。

注冊bean定義層面
基於XML的配置形式是這樣:

  1.  
    <bean id= "mockService" class="..MockServiceImpl">
  2.  
    ...
  3.  
    </bean>

而基於JavaConfig的配置形式是這樣的:

  1.  
    @Configuration
  2.  
    public class MockConfiguration{
  3.  
    @Bean
  4.  
    public MockService mockService(){
  5.  
    return new MockServiceImpl();
  6.  
    }
  7.  
    }

任何一個標注了@Bean的方法,其返回值將作為一個bean定義注冊到Spring的IoC容器,方法名將默認成該bean定義的id。

表達依賴注入關系層面
為了表達bean與bean之間的依賴關系,在XML形式中一般是這樣:

  1.  
    <bean id= "mockService" class="..MockServiceImpl">
  2.  
    <propery name ="dependencyService" ref="dependencyService" />
  3.  
    </bean>
  4.  
     
  5.  
    <bean id= "dependencyService" class="DependencyServiceImpl"></bean>

而基於JavaConfig的配置形式是這樣的:

  1.  
    @Configuration
  2.  
    public class MockConfiguration{
  3.  
    @Bean
  4.  
    public MockService mockService(){
  5.  
    return new MockServiceImpl(dependencyService());
  6.  
    }
  7.  
     
  8.  
    @Bean
  9.  
    public DependencyService dependencyService(){
  10.  
    return new DependencyServiceImpl();
  11.  
    }
  12.  
    }

如果一個bean的定義依賴其他bean,則直接調用對應的JavaConfig類中依賴bean的創建方法就可以了。

@ComponentScan

@ComponentScan這個注解在Spring中很重要,它對應XML配置中的元素,@ComponentScan的功能其實就是自動掃描並加載符合條件的組件(比如@Component和@Repository等)或者bean定義,最終將這些bean定義加載到IoC容器中。

我們可以通過basePackages等屬性來細粒度的定制@ComponentScan自動掃描的范圍,如果不指定,則默認Spring框架實現會從聲明@ComponentScan所在類的package進行掃描。

注:所以SpringBoot的啟動類最好是放在root package下,因為默認不指定basePackages。

@EnableAutoConfiguration

個人感覺@EnableAutoConfiguration這個Annotation最為重要,所以放在最后來解讀,大家是否還記得Spring框架提供的各種名字為@Enable開頭的Annotation定義?比如@EnableScheduling、@EnableCaching、@EnableMBeanExport等,@EnableAutoConfiguration的理念和做事方式其實一脈相承,簡單概括一下就是,借助@Import的支持,收集和注冊特定場景相關的bean定義。

@EnableScheduling是通過@Import將Spring調度框架相關的bean定義都加載到IoC容器。
@EnableMBeanExport是通過@Import將JMX相關的bean定義加載到IoC容器。
而@EnableAutoConfiguration也是借助@Import的幫助,將所有符合自動配置條件的bean定義加載到IoC容器,僅此而已!

@EnableAutoConfiguration作為一個復合Annotation,其自身定義關鍵信息如下:

  1.  
    @SuppressWarnings("deprecation")
  2.  
    @Target(ElementType.TYPE)
  3.  
    @Retention(RetentionPolicy.RUNTIME)
  4.  
    @Documented
  5.  
    @Inherited
  6.  
    @AutoConfigurationPackage
  7.  
    @Import(EnableAutoConfigurationImportSelector.class)
  8.  
    public @interface EnableAutoConfiguration {
  9.  
    ...
  10.  
    }

兩個比較重要的注解:

@AutoConfigurationPackage:自動配置包

@Import: 導入自動配置的組件

AutoConfigurationPackage注解:

  1.  
    static class Registrar implements ImportBeanDefinitionRegistrar, DeterminableImports {
  2.  
     
  3.  
    @Override
  4.  
    public void registerBeanDefinitions(AnnotationMetadata metadata,
  5.  
    BeanDefinitionRegistry registry) {
  6.  
    register(registry, new PackageImport(metadata).getPackageName());
  7.  
    }

它其實是注冊了一個Bean的定義。

new PackageImport(metadata).getPackageName(),它其實返回了當前主程序類的 同級以及子級 的包組件。

以上圖為例,DemoApplication是和demo包同級,但是demo2這個類是DemoApplication的父級,和example包同級

也就是說,DemoApplication啟動加載的Bean中,並不會加載demo2,這也就是為什么,我們要把DemoApplication放在項目的最高級中。

Import(AutoConfigurationImportSelector.class)注解:

可以從圖中看出 AutoConfigurationImportSelector 繼承了 DeferredImportSelector 繼承了 ImportSelector

ImportSelector有一個方法為:selectImports。

  1.  
    @Override
  2.  
    public String[] selectImports(AnnotationMetadata annotationMetadata) {
  3.  
    if (!isEnabled(annotationMetadata)) {
  4.  
    return NO_IMPORTS;
  5.  
    }
  6.  
    AutoConfigurationMetadata autoConfigurationMetadata = AutoConfigurationMetadataLoader
  7.  
    .loadMetadata( this.beanClassLoader);
  8.  
    AnnotationAttributes attributes = getAttributes(annotationMetadata);
  9.  
    List<String> configurations = getCandidateConfigurations(annotationMetadata,
  10.  
    attributes);
  11.  
    configurations = removeDuplicates(configurations);
  12.  
    Set<String> exclusions = getExclusions(annotationMetadata, attributes);
  13.  
    checkExcludedClasses(configurations, exclusions);
  14.  
    configurations.removeAll(exclusions);
  15.  
    configurations = filter(configurations, autoConfigurationMetadata);
  16.  
    fireAutoConfigurationImportEvents(configurations, exclusions);
  17.  
    return StringUtils.toStringArray(configurations);
  18.  
    }

可以看到第九行,它其實是去加載 public static final String FACTORIES_RESOURCE_LOCATION = "META-INF/spring.factories";外部文件。這個外部文件,有很多自動配置的類。如下:

image

其中,最關鍵的要屬@Import(EnableAutoConfigurationImportSelector.class),借助EnableAutoConfigurationImportSelector,@EnableAutoConfiguration可以幫助SpringBoot應用將所有符合條件的@Configuration配置都加載到當前SpringBoot創建並使用的IoC容器。就像一只“八爪魚”一樣。

自動配置幕后英雄:SpringFactoriesLoader詳解

借助於Spring框架原有的一個工具類:SpringFactoriesLoader的支持,@EnableAutoConfiguration可以智能的自動配置功效才得以大功告成!

SpringFactoriesLoader屬於Spring框架私有的一種擴展方案,其主要功能就是從指定的配置文件META-INF/spring.factories加載配置。

  1.  
    public abstract class SpringFactoriesLoader {
  2.  
    //...
  3.  
    public static <T> List<T> loadFactories(Class<T> factoryClass, ClassLoader classLoader) {
  4.  
    ...
  5.  
    }
  6.  
     
  7.  
     
  8.  
    public static List<String> loadFactoryNames(Class<?> factoryClass, ClassLoader classLoader) {
  9.  
    ....
  10.  
    }
  11.  
    }

配合@EnableAutoConfiguration使用的話,它更多是提供一種配置查找的功能支持,即根據@EnableAutoConfiguration的完整類名org.springframework.boot.autoconfigure.EnableAutoConfiguration作為查找的Key,獲取對應的一組@Configuration類

上圖就是從SpringBoot的autoconfigure依賴包中的META-INF/spring.factories配置文件中摘錄的一段內容,可以很好地說明問題。

所以,@EnableAutoConfiguration自動配置的魔法騎士就變成了:從classpath中搜尋所有的META-INF/spring.factories配置文件,並將其中org.springframework.boot.autoconfigure.EnableutoConfiguration對應的配置項通過反射(Java Refletion)實例化為對應的標注了@Configuration的JavaConfig形式的IoC容器配置類,然后匯總為一個並加載到IoC容器。

SpringBoot原理圖


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM