自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

五分鐘說清楚 Spring Boot的自動配置原理

開發(fā) 架構(gòu)
Spring Boot沒有火起來之前,使用SSM架構(gòu)的項目那是相當?shù)亩?,現(xiàn)在也有不少項目還是使用這種架構(gòu)。

[[381634]]

前言

Spring Boot沒有火起來之前,使用SSM架構(gòu)的項目那是相當?shù)亩?,現(xiàn)在也有不少項目還是使用這種架構(gòu)。在使用SSM架構(gòu)的時候,大家是否還記得大量配置的煩惱郁悶,各種配置,搞得人都不是很爽。各種配置掃描,如果想添加一個新的依賴,還得添加各種配置。這種大量配置的工作不進浪費時間,最主要的是會產(chǎn)生各種坑。

自從有了 Spring Boot 之后,咱們就爽爽的!各種零配置開箱即用,而我們之所以開發(fā)起來能夠這么爽,自動配置的功勞少不了,今天我們就一起來討論一下 SpringBoot 自動配置原理。

快速了解 SpringBoot 源碼常用注解

我們先對相關(guān)基本的注解進行說明,熟悉了這些注解,有利于我們后面更好的閱讀源碼。只要搞清楚了這些注解,遠嗎也就變得沒那么難了。加油!少年~

組合注解

當可能大量同時使用到幾個注解到同一個類上,就可以考慮將這幾個注解到別的注解上。被注解的注解我們就稱之為組合注解。

  • 元注解:可以注解到別的注解上的注解。
  • 組合注解:被注解的注解我們就稱之為組合注解。

@Value

@Value注解有Spring提供,并非是Spring Boot中的,該注解存在于spring-beans.jar中。

  1. @Target({ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.ANNOTATION_TYPE}) 
  2. @Retention(RetentionPolicy.RUNTIME) 
  3. @Documented 
  4. public @interface Value { 
  5.  /** 
  6.   * The actual value expression: for example {@code #{systemProperties.myProp}}. 
  7.   * 比如我們配置項address=ZhongguoGuizhou,這里的value=address 
  8.   */ 
  9.  String value(); 

@Value也相當于傳統(tǒng) xml 配置文件中的 value 字段。

假設(shè)存在代碼:

  1. @Component  
  2. public class Person {  
  3.  
  4. @Value("i am name")  
  5. private String name;  
  6.  

上面代碼等價于的配置文件:

  1. <bean class="Person">  
  2.   <property name ="name" value="i am name"></property> 
  3. </bean>  

我們知道配置文件中的 value 的取值可以是:

  • 字面量
  • 通過 ${key} 方式從環(huán)境變量中獲取值
  • 通過 ${key} 方式全局配置文件中獲取值
  • #{SpEL}

所以,我們就可以通過 @Value(${key}) 的方式獲取全局配置文件中的指定配置項。

使用@Value有三個缺點:

  • 配置屬性不統(tǒng)一,沒有結(jié)構(gòu)。
  • 注入麻煩每個屬性都要寫配置名,和屬性名。(只要有重復(fù)的工作,就應(yīng)該重構(gòu))
  • 配置零散在項目中各處

@ConfigurationProperties 注解

該注解有Spring Boot提供,在spring-boot.jar包中

org.springframework.boot.context.properties;目錄下:

  1. @Target({ElementType.TYPE, ElementType.METHOD}) 
  2. @Retention(RetentionPolicy.RUNTIME) 
  3. @Documented 
  4. public @interface ConfigurationProperties { 
  5.     //前綴 
  6.     @AliasFor("prefix"
  7.     String value() default ""
  8.  
  9.     @AliasFor("value"
  10.     String prefix() default "";  
  11.     //... 

如果我們要去獲取很多配置項,比如:賬號、密碼、地址等一堆配置項時,如果我們還是用@Value得一個一個去獲取配置項,是不是覺得很low呀,所以這時候我們就可以考慮使用@ConfigurationProperties。

標有 @ConfigurationProperties 的類的所有屬性和配置文件中相關(guān)的配置項進行綁定。(默認從全局配置文件中獲取配置值),綁定之后我們就可以通過這個類去訪問全局配置文件中的屬性值了。

下面看一個實例:

第1步:在主配置文件中添加如下配置

  1. pay.account=java后端技術(shù)全棧  
  2. pay.password=tj20120622 
  3. pay.url=http://woaijava.cc 

第2步:創(chuàng)建配置類,由于篇幅問題這里省略了 setter、getter 方法,但是實際開發(fā)中這個是必須的,否則無法成功注入。另外,@Component 這個注解也還是需要添加的。

  1. @Component  
  2.     @ConfigurationProperties(prefix = "pay")  
  3.     public class PayInfo {  
  4.      
  5.     private String account;  
  6.     private Integer password;  
  7.     private String url;  
  8.      
  9.     }  

這里 @ConfigurationProperties 有一個 prefix 參數(shù),主要是用來指定該配置項在配置文件中的前綴。

第3步:測試,在 Spring Boot 環(huán)境中,編寫個測試方法,注入PayInfo類,即可通過 PayInfo對象取到配置文件的值。

@Import 【Spring 提供】

@Import 是由Spring提供的注解,支持導(dǎo)入普通 java 類,并將其聲明成一個bean。主要用于將多個分散的 java config 配置類融合成一個更大的 config 類。

  • @Import 注解在 4.2 之前只支持導(dǎo)入配置類。
  • 在4.2之后 @Import 注解支持導(dǎo)入普通的 java 類,并將其聲明成一個 bean。

@Import 三種使用方式

  • 直接導(dǎo)入普通的 Java 類。
  • 配合自定義的 ImportSelector 使用。
  • 配合 ImportBeanDefinitionRegistrar 使用。

第一種方式:直接導(dǎo)入普通的 Java 類

第1步:創(chuàng)建一個普通的 Java 類。

  1. public class Circle {  
  2.      public void sayHi() {  
  3.        System.out.println("Circle sayHi()");  
  4.      }  
  5.    }  

第2步:創(chuàng)建一個配置類,里面沒有顯式聲明任何的 Bean,然后將剛才創(chuàng)建的 Circle 導(dǎo)入。

  1. @Import({Circle.class})  
  2.     @Configuration  
  3.     public class MainConfig {  
  4.      
  5.     }  

第3步:創(chuàng)建測試類。

  1. public static void main(String[] args) {  
  2.     
  3.    ApplicationContext context = new AnnotationConfigApplicationContext(MainConfig.class);  
  4.    Circle circle = context.getBean(Circle.class);  
  5.    circle.sayHi();  
  6.     
  7.    }  

第4步:運行結(jié)果:

  1. Circle sayHi() 

可以看到我們順利的從 IOC 容器中獲取到了 Circle 對象,證明我們在配置類中導(dǎo)入的 Circle 類,確實被聲明為了一個 Bean。

第二種方式:配合自定義的 ImportSelector 使用

ImportSelector 是一個接口,該接口中只有一個 selectImports 方法,用于返回全類名數(shù)組。所以利用該特性我們可以給容器動態(tài)導(dǎo)入 N 個 Bean。

第1步:創(chuàng)建普通 Java 類 Triangle。

  1. public class Triangle {  
  2.         public void sayHi(){  
  3.         System.out.println("Triangle sayHi()");  
  4.         }  
  5.     } 

第2步:創(chuàng)建 ImportSelector 實現(xiàn)類,selectImports 返回 Triangle 的全類名。

  1. public class MyImportSelector implements ImportSelector {  
  2.        @Override  
  3.        public String[] selectImports(AnnotationMetadata annotationMetadata) {  
  4.        return new String[]{"annotation.importannotation.waytwo.Triangle"};  
  5.        }  
  6.    }  

第3步:創(chuàng)建配置類,在原來的基礎(chǔ)上還導(dǎo)入了 MyImportSelector。

  1. @Import({Circle.class,MyImportSelector.class})  
  2.     @Configuration  
  3.     public class MainConfigTwo {  
  4.      
  5.     }  

第4步:創(chuàng)建測試類

  1. public static void main(String[] args) {  
  2.    
  3.       ApplicationContext context = new AnnotationConfigApplicationContext(MainConfigTwo.class);  
  4.       Circle circle = context.getBean(Circle.class);  
  5.       Triangle triangle = context.getBean(Triangle.class);  
  6.       circle.sayHi();  
  7.       triangle.sayHi();  
  8.    
  9.   }  

第5步:運行結(jié)果:

Circle sayHi()

Triangle sayHi()

可以看到 Triangle 對象也被 IOC 容器成功的實例化出來了。

第三種方式:配合 ImportBeanDefinitionRegistrar 使用

ImportBeanDefinitionRegistrar 也是一個接口,它可以手動注冊bean到容器中,從而我們可以對類進行個性化的定制。(需要搭配 @Import 與 @Configuration 一起使用。)

第1步:創(chuàng)建普通 Java 類 Rectangle。

  1. public class Rectangle {  
  2.     public void sayHi() {  
  3.     System.out.println("Rectangle sayHi()");  
  4.     }  

第2步:創(chuàng)建 ImportBeanDefinitionRegistrar 實現(xiàn)類,實現(xiàn)方法直接手動注冊一個名叫 rectangle 的 Bean 到 IOC 容器中。

  1. public class MyImportBeanDefinitionRegistrar implements ImportBeanDefinitionRegistrar {  
  2.      
  3.     @Override  
  4.     public void registerBeanDefinitions(AnnotationMetadata annotationMetadata, BeanDefinitionRegistry beanDefinitionRegistry) {  
  5.      
  6.     RootBeanDefinition rootBeanDefinition = new RootBeanDefinition(Rectangle.class);  
  7.     // 注冊一個名字叫做 rectangle 的 bean  
  8.     beanDefinitionRegistry.registerBeanDefinition("rectangle", rootBeanDefinition);  
  9.     }  
  10.      
  11. }  

第3步:創(chuàng)建配置類,導(dǎo)入 MyImportBeanDefinitionRegistrar 類。

  1. @Import({Circle.class, MyImportSelector.class, MyImportBeanDefinitionRegistrar.class})  
  2. @Configuration  
  3. public class MainConfigThree {  
  4. }  

第4步:創(chuàng)建測試類。

  1. public static void main(String[] args) {  
  2.      
  3. ApplicationContext context = new AnnotationConfigApplicationContext(MainConfigThree.class);  
  4.     Circle circle = context.getBean(Circle.class);  
  5.     Triangle triangle = context.getBean(Triangle.class);  
  6.     Rectangle rectangle = context.getBean(Rectangle.class);  
  7.     circle.sayHi();  
  8.     triangle.sayHi();  
  9.     rectangle.sayHi();  

第5步:運行結(jié)果

Circle sayHi()

Triangle sayHi()

Rectangle sayHi()

由此看一看到,Rectangle 對象也被注冊進來了。

@Conditional 【Spring提供】

@Conditional 注釋可以實現(xiàn)只有在特定條件滿足時才啟用一些配置。

下面看一個簡單的例子:

第1步:創(chuàng)建普通 Java 類 ConditionBean,該類主要用來驗證 Bean 是否成功加載。

  1. public class ConditionBean {  
  2.     public void sayHi() {  
  3.       System.out.println("ConditionBean sayHi()");  
  4.     }  
  5. }  

第2步:創(chuàng)建 Condition 實現(xiàn)類,@Conditional 注解只有一個 Condition 類型的參數(shù),Condition 是一個接口,該接口只有一個返回布爾值的 matches() 方法,該方法返回 true 則條件成立,配置類生效。反之,則不生效。在該例子中我們直接返回 true。

  1. public class MyCondition implements Condition {  
  2.      
  3.     @Override  
  4.     public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) {  
  5.       return true;  
  6.     }  
  7. }  

第3步:創(chuàng)建配置類,可以看到該配置的 @Conditional 傳了我們剛才創(chuàng)建的 Condition 實現(xiàn)類進去,用作條件判斷。

  1. @Configuration  
  2. @Conditional(MyCondition.class)  
  3. public class ConditionConfig {  
  4.     @Bean  
  5.     public ConditionBean conditionBean(){  
  6.      return new ConditionBean();  
  7.     }  
  8. }  

第4步:編寫測試方法。

  1. public static void main(String[] args) {  
  2.   ApplicationContext context = new AnnotationConfigApplicationContext(ConditionConfig.class);  
  3.   ConditionBean conditionBean = context.getBean(ConditionBean.class);  
  4.   conditionBean.sayHi();  
  5. }  

第5步:結(jié)果分析

因為 Condition 的 matches 方法直接返回了 true,配置類會生效,我們可以把 matches 改成返回 false,則配置類就不會生效了。

除了自定義 Condition,Spring 還為我們擴展了一些常用的 Condition。常用注解,可以參考:

SpringBoot 啟動過程

在看源碼的過程中,我們會看到以下四個類的方法經(jīng)常會被調(diào)用,我們需要對一下幾個類有點印象:

  • ApplicationContextInitializer
  • ApplicationRunner
  • CommandLineRunner
  • SpringApplicationRunListener

下面開始源碼分析,先從 SpringBoot 的啟動類的 run() 方法開始看,以下是調(diào)用鏈:SpringApplication.run() -> run(new Class[]{primarySource}, args) -> new SpringApplication(primarySources)).run(args)。

一直在run,終于到重點了,我們直接看 new SpringApplication(primarySources)).run(args) 這個方法。

上面的方法主要包括兩大步驟:

  • 創(chuàng)建 SpringApplication 對象。
  • 運行 run() 方法。

創(chuàng)建 SpringApplication 對象

  1. public SpringApplication(ResourceLoader resourceLoader, Class... primarySources) {  
  2.      
  3.     this.sources = new LinkedHashSet();  
  4.     this.bannerMode = Mode.CONSOLE;  
  5.     this.logStartupInfo = true;  
  6.     this.addCommandLineProperties = true;  
  7.     this.addConversionService = true;  
  8.     this.headless = true;  
  9.     this.registerShutdownHook = true;  
  10.     this.additionalProfiles = new HashSet();  
  11.     this.isCustomEnvironment = false;  
  12.     this.resourceLoader = resourceLoader;  
  13.     Assert.notNull(primarySources, "PrimarySources must not be null");  
  14.     // 保存主配置類(這里是一個數(shù)組,說明可以有多個主配置類)  
  15.     this.primarySources = new LinkedHashSet(Arrays.asList(primarySources));  
  16.     // 判斷當前是否是一個 Web 應(yīng)用  
  17.     this.webApplicationType = WebApplicationType.deduceFromClasspath();  
  18.     // 從類路徑下找到 META/INF/Spring.factories 配置的所有 ApplicationContextInitializer,然后保存起來  
  19.     this.setInitializers(this.getSpringFactoriesInstances(ApplicationContextInitializer.class));  
  20.     // 從類路徑下找到 META/INF/Spring.factories 配置的所有 ApplicationListener,然后保存起來  
  21.     this.setListeners(this.getSpringFactoriesInstances(ApplicationListener.class));  
  22.     // 從多個配置類中找到有 main 方法的主配置類(只有一個)  
  23.     this.mainApplicationClass = this.deduceMainApplicationClass();  
  24.      
  25. }  

運行 run() 方法

  1. public ConfigurableApplicationContext run(String... args) {  
  2.      
  3.     // 創(chuàng)建計時器  
  4.     StopWatch stopWatch = new StopWatch();  
  5.     stopWatch.start();  
  6.     // 聲明 IOC 容器  
  7.     ConfigurableApplicationContext context = null;  
  8.     Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList();  
  9.     this.configureHeadlessProperty();  
  10.     // 從類路徑下找到 META/INF/Spring.factories 獲取 SpringApplicationRunListeners  
  11.     SpringApplicationRunListeners listeners = this.getRunListeners(args);  
  12.     // 回調(diào)所有 SpringApplicationRunListeners 的 starting() 方法  
  13.     listeners.starting();  
  14.     Collection exceptionReporters;  
  15.     try {  
  16.     // 封裝命令行參數(shù)  
  17.     ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);  
  18.     // 準備環(huán)境,包括創(chuàng)建環(huán)境,創(chuàng)建環(huán)境完成后回調(diào) SpringApplicationRunListeners#environmentPrepared()方法,表示環(huán)境準備完成  
  19.     ConfigurableEnvironment environment = this.prepareEnvironment(listeners, applicationArguments);  
  20.     this.configureIgnoreBeanInfo(environment);  
  21.     // 打印 Banner  
  22.     Banner printedBanner = this.printBanner(environment);  
  23.     // 創(chuàng)建 IOC 容器(決定創(chuàng)建 web 的 IOC 容器還是普通的 IOC 容器)  
  24.     context = this.createApplicationContext();  
  25.     exceptionReporters = this.getSpringFactoriesInstances(SpringBootExceptionReporter.class, new Class[]{ConfigurableApplicationContext.class}, context);  
  26.     /* 
  27.      * 準備上下文環(huán)境,將 environment 保存到 IOC 容器中,并且調(diào)用 applyInitializers() 方法 
  28.      * applyInitializers() 方法回調(diào)之前保存的所有的 ApplicationContextInitializer 的 initialize() 方法 
  29.      * 然后回調(diào)所有的 SpringApplicationRunListener#contextPrepared() 方法  
  30.      * 最后回調(diào)所有的 SpringApplicationRunListener#contextLoaded() 方法  
  31.      */ 
  32.     this.prepareContext(context, environment, listeners, applicationArguments, printedBanner);  
  33.     // 刷新容器,IOC 容器初始化(如果是 Web 應(yīng)用還會創(chuàng)建嵌入式的 Tomcat),掃描、創(chuàng)建、加載所有組件的地方  
  34.     this.refreshContext(context);  
  35.     // 從 IOC 容器中獲取所有的 ApplicationRunner 和 CommandLineRunner 進行回調(diào)  
  36.     this.afterRefresh(context, applicationArguments);  
  37.     stopWatch.stop();  
  38.     if (this.logStartupInfo) {  
  39.     (new StartupInfoLogger(this.mainApplicationClass)).logStarted(this.getApplicationLog(), stopWatch);  
  40.     }  
  41.     // 調(diào)用 所有 SpringApplicationRunListeners#started()方法  
  42.     listeners.started(context);  
  43.     this.callRunners(context, applicationArguments);  
  44.     } catch (Throwable var10) {  
  45.     this.handleRunFailure(context, var10, exceptionReporters, listeners);  
  46.     throw new IllegalStateException(var10);  
  47.     }  
  48.     try {  
  49.     listeners.running(context);  
  50.     return context;  
  51.     } catch (Throwable var9) {  
  52.     this.handleRunFailure(context, var9, exceptionReporters, (SpringApplicationRunListeners)null);  
  53.     throw new IllegalStateException(var9);  
  54.     }  
  55. }  

小結(jié)

run() 階段主要就是回調(diào)本節(jié)開頭提到過的4個監(jiān)聽器中的方法與加載項目中組件到 IOC 容器中,而所有需要回調(diào)的監(jiān)聽器都是從類路徑下的 META-INF/Spring.factories中獲取,從而達到啟動前后的各種定制操作。

SpringBoot 自動配置原理

@SpringBootApplication 注解

SpringBoot 項目的一切都要從 @SpringBootApplication 這個注解開始說起。

@SpringBootApplication 標注在某個類上說明:

  • 這個類是 SpringBoot 的主配置類。
  • SpringBoot 就應(yīng)該運行這個類的 main 方法來啟動 SpringBoot 應(yīng)用。

該注解的定義如下:

  1. @SpringBootConfiguration  
  2. @EnableAutoConfiguration  
  3. @ComponentScan(  
  4. excludeFilters = {@Filter(  
  5.   type = FilterType.CUSTOM,  
  6.   classes = {TypeExcludeFilter.class}  
  7. ), @Filter(  
  8.     type = FilterType.CUSTOM,  
  9.     classes = {AutoConfigurationExcludeFilter.class}  
  10. )}  
  11. )  
  12. public @interface SpringBootApplication {  
  13.      

可以看到SpringBootApplication 注解是一個組合注解(關(guān)于組合注解文章的開頭有講到),其主要組合了一下三個注解:

  • @SpringBootConfiguration:該注解表示這是一個 Spring Boot 的配置類,其實它就是一個 @Configuration 注解而已。
  • @ComponentScan:開啟組件掃描。
  • @EnableAutoConfiguration:從名字就可以看出來,就是這個類開啟自動配置的。嗯,自動配置的奧秘全都在這個注解里面。

@EnableAutoConfiguration 注解

先看該注解是怎么定義的:

  1. @AutoConfigurationPackage  
  2. @Import({AutoConfigurationImportSelector.class})  
  3. public @interface EnableAutoConfiguration {  

@AutoConfigurationPackage

從字面意思理解就是自動配置包。點進去可以看到就是一個 @Import 注解:@Import({Registrar.class}),導(dǎo)入了一個 Registrar 的組件。關(guān)于 @Import 的用法文章上面也有介紹哦。

我們在 Registrar 類中的 registerBeanDefinitions 方法上打上斷點,可以看到返回了一個包名,該包名其實就是主配置類所在的包。

一句話:@AutoConfigurationPackage 注解就是將主配置類(@SpringBootConfiguration標注的類)的所在包及下面所有子包里面的所有組件掃描到Spring容器中。所以說,默認情況下主配置類包及子包以外的組件,Spring 容器是掃描不到的。

@Import({AutoConfigurationImportSelector.class})

該注解給當前配置類導(dǎo)入另外的 N 個自動配置類。(該注解詳細用法上文有提及)。

配置類導(dǎo)入規(guī)則

那具體的導(dǎo)入規(guī)則是什么呢?我們來看一下源碼。在開始看源碼之前,先啰嗦兩句。就像小馬哥說的,我們看源碼不用全部都看,不用每一行代碼都弄明白是什么意思,我們只要抓住關(guān)鍵的地方就可以了。

我們知道 AutoConfigurationImportSelector 的 selectImports就是用來返回需要導(dǎo)入的組件的全類名數(shù)組的,那么如何得到這些數(shù)組呢?

在 selectImports 方法中調(diào)用了一個 getAutoConfigurationEntry() 方法。

由于篇幅問題我就不一一截圖了,我直接告訴你們調(diào)用鏈:在 `getAutoConfigurationEntry() -> getCandidateConfigurations() -> loadFactoryNames()``。

在這里 loadFactoryNames()方法傳入了 EnableAutoConfiguration.class 這個參數(shù)。先記住這個參數(shù),等下會用到。

loadFactoryNames() 中關(guān)鍵的三步:

  • 從當前項目的類路徑中獲取所有 META-INF/spring.factories 這個文件下的信息。
  • 將上面獲取到的信息封裝成一個 Map 返回。
  • 從返回的 Map 中通過剛才傳入的 EnableAutoConfiguration.class 參數(shù),獲取該 key 下的所有值。

META-INF/spring.factories 探究

聽我這樣說完可能會有點懵,我們來看一下 META-INF/spring.factories 這類文件是什么就不懵了。當然在很多第三方依賴中都會有這個文件,一般每導(dǎo)入一個第三方的依賴,除了本身的jar包以外,還會有一個 xxx-spring-boot-autoConfigure,這個就是第三方依賴自己編寫的自動配置類。我們現(xiàn)在就以 spring-boot-autocongigure 這個依賴來說。

可以看到 EnableAutoConfiguration 下面有很多類,這些就是我們項目進行自動配置的類。

一句話:將類路徑下META-INF/spring.factories 里面配置的所有 EnableAutoConfiguration 的值加入到 Spring 容器中。

HttpEncodingAutoConfiguration

通過上面方式,所有的自動配置類就被導(dǎo)進主配置類中了。但是這么多的配置類,明顯有很多自動配置我們平常是沒有使用到的,沒理由全部都生效吧。

接下來我們以 HttpEncodingAutoConfiguration為例來看一個自動配置類是怎么工作的。為啥選這個類呢?主要是這個類比較的簡單典型。

先看一下該類標有的注解:

  1. @Configuration  
  2. @EnableConfigurationProperties({HttpProperties.class})  
  3. @ConditionalOnWebApplication(  
  4.  type = Type.SERVLET  
  5. )  
  6. @ConditionalOnClass({CharacterEncodingFilter.class})  
  7. @ConditionalOnProperty(  
  8.   prefix = "spring.http.encoding",  
  9.   value = {"enabled"},  
  10.   matchIfMissing = true  
  11. )  
  12. public class HttpEncodingAutoConfiguration {  
  13.      
  • @Configuration:標記為配置類。
  • @ConditionalOnWebApplication:web應(yīng)用下才生效。
  • @ConditionalOnClass:指定的類(依賴)存在才生效。
  • @ConditionalOnProperty:主配置文件中存在指定的屬性才生效。
  • @EnableConfigurationProperties({HttpProperties.class}):啟動指定類的ConfigurationProperties功能;將配置文件中對應(yīng)的值和 HttpProperties 綁定起來;并把 HttpProperties 加入到 IOC 容器中。

因為@EnableConfigurationProperties({HttpProperties.class})把配置文件中的配置項與當前 HttpProperties 類綁定上了。

然后在HttpEncodingAutoConfiguration 中又引用了 HttpProperties ,所以最后就能在 HttpEncodingAutoConfiguration中使用配置文件中的值了。

最終通過 @Bean 和一些條件判斷往容器中添加組件,實現(xiàn)自動配置。(當然該Bean中屬性值是從 HttpProperties 中獲取)

HttpProperties

HttpProperties 通過 @ConfigurationProperties 注解將配置文件與自身屬性綁定。

所有在配置文件中能配置的屬性都是在 xxxProperties 類中封裝著;配置文件能配置什么就可以參照某個功能對應(yīng)的這個屬性類。

  1. @ConfigurationProperties(  
  2.   prefix = "spring.http"  
  3. )// 從配置文件中獲取指定的值和bean的屬性進行綁定  
  4. public class HttpProperties {  

總結(jié)

  • SpringBoot啟動會加載大量的自動配置類。
  • 我們看需要的功能有沒有SpringBoot默認寫好的自動配置類。
  • 我們再來看這個自動配置類中到底配置了那些組件(只要我們要用的組件有,我們就不需要再來配置了)。
  • 給容器中自動配置類添加組件的時候,會從properties類中獲取某些屬性。我們就可以在配置文件中指定這些屬性的值。xxxAutoConfiguration:自動配置類給容器中添加組件。xxxProperties:封裝配置文件中相關(guān)屬性。

用心看的小伙伴應(yīng)該發(fā)現(xiàn)了,其實很多需要待加載的類都放在類路徑下的META-INF/Spring.factories文件下,而不是直接寫死這代碼中,這樣做就可以很方便我們自己或第三方去z做擴展。

參考:

kil51.cn/JTg9D

blog.51cto.com/4247649/2118354

www.cnblogs.com/duanxz/p/3787757.html

www.jianshu.com/p/e22b9fef311c

blog.csdn.net/qq_26525215/article/details/53523970

http://www.woaijava.cc

本文轉(zhuǎn)載自微信公眾號「Java后端技術(shù)全?!?,可以通過以下二維碼關(guān)注。轉(zhuǎn)載本文請聯(lián)系Java后端技術(shù)全棧公眾號。

 

責任編輯:武曉燕 來源: Java后端技術(shù)全棧
相關(guān)推薦

2018-11-28 11:08:30

并查集集合數(shù)據(jù)結(jié)構(gòu)

2012-10-12 09:23:04

JavaEEUMLObject

2024-09-23 05:10:00

微服務(wù)CORSSpringBoot

2019-02-21 16:24:28

5G火車站設(shè)備

2021-12-01 06:50:50

Docker底層原理

2023-10-09 16:35:19

方案Spring支付

2020-03-02 15:17:37

云原生CNCF容器

2022-05-30 08:05:11

架構(gòu)

2023-01-26 01:09:31

配置數(shù)據(jù)源參數(shù)

2023-10-06 19:21:49

Initializr應(yīng)用Spring

2019-07-04 09:13:04

中臺百度團隊

2021-02-25 08:21:38

高可用風險故障

2021-11-08 18:37:45

MySQL解碼測試

2019-09-26 09:24:01

GC原理調(diào)優(yōu)

2020-10-29 10:35:53

Nginx架構(gòu)服務(wù)器

2022-02-16 19:42:25

Spring配置開發(fā)

2020-05-12 09:10:24

瀏覽器服務(wù)器網(wǎng)絡(luò)

2020-12-18 07:33:20

SpringSchedule組件

2022-11-11 15:49:41

MySQL隔離

2009-11-17 12:47:05

PHP配置
點贊
收藏

51CTO技術(shù)棧公眾號