1. 程式人生 > >spring boot學習二:Spring Boot自動裝配分析與實戰

spring boot學習二:Spring Boot自動裝配分析與實戰

Web application conditions:@ConditionalOnWebApplication和@ConditionalOnNotWebApplication,當專案是web專案,或者不是web專案的條件註解

SpEL expression conditions:@ConditionalOnExpression,根據SPEL表示式執行結果作為條件

自動裝配程式碼跟蹤:

我們從上一章節的@SpringBootApplication開始,由於@SpringBootApplication是由@EnableAutoConfiguration組成的,我們觀察@EnableAutoConfiguration註解的原始碼如下:

Java程式碼 
  1. //  
  2. // Source code recreated from a .class file by IntelliJ IDEA  
  3. // (powered by Fernflower decompiler)  
  4. //  
  5. package org.springframework.boot.autoconfigure;  
  6. import java.lang.annotation.Documented;  
  7. import java.lang.annotation.ElementType;  
  8. import java.lang.annotation.Inherited;  
  9. import
     java.lang.annotation.Retention;  
  10. import java.lang.annotation.RetentionPolicy;  
  11. import java.lang.annotation.Target;  
  12. import org.springframework.context.annotation.Import;  
  13. @Target({ElementType.TYPE})  
  14. @Retention(RetentionPolicy.RUNTIME)  
  15. @Documented  
  16. @Inherited  
  17. @AutoConfigurationPackage  
  18. @Import
    ({EnableAutoConfigurationImportSelector.class})  
  19. public @interface EnableAutoConfiguration {  
  20.     String ENABLED_OVERRIDE_PROPERTY = "spring.boot.enableautoconfiguration";  
  21.     Class<?>[] exclude() default {};  
  22.     String[] excludeName() default {};  
  23. }  

 EnableAutoConfiguration使用@Import註解將EnableAutoConfigurationImportSelector匯入並宣告為一個Bean,跟蹤EnableAutoConfigurationImportSelector的原始碼,發現其繼承AutoConfigurationImportSelector類,而其中有這麼一個方法getCandidateConfigurations

Java程式碼 
  1. protected List<String> getCandidateConfigurations(AnnotationMetadata metadata,AnnotationAttributes attributes) {  
  2.         List<String> configurations = SpringFactoriesLoader.loadFactoryNames(this.getSpringFactoriesLoaderFactoryClass(), this.getBeanClassLoader());  
  3.        //...省略其餘程式碼  
  4.     }  
繼續跟蹤SpringFactoriesLoader.loadFactoryNames方法,其程式碼如下: Java程式碼 
  1. public static List<String> loadFactoryNames(Class<?> factoryClass, ClassLoader classLoader) {  
  2.      String factoryClassName = factoryClass.getName();  
  3.      try {  
  4.         Enumeration<URL> urls = classLoader != null ? classLoader.getResources("META-INF/spring.factories") :ClassLoader.getSystemResources("META-INF/spring.factories");  
  5.         ArrayList result = new ArrayList();  
  6.         while(urls.hasMoreElements()) {  
  7.             URL url = (URL)urls.nextElement();  
  8.             Properties properties = PropertiesLoaderUtils.loadProperties(new UrlResource(url));  
  9.             String factoryClassNames = properties.getProperty(factoryClassName);  
  10.             result.addAll(Arrays.asList(StringUtils.commaDelimitedListToStringArray(factoryClassNames)));  
  11.          }  

 發現最終讀取的就是META-INF/spring.factories檔案,點選intellij中【External Libraries】中spring-boot-autoconfigure-1.5.7.RELEASE.jar,開啟META-INF/spring.factories檔案,檢視裡面內容