spring boot學習二:Spring Boot自動裝配分析與實戰
阿新 • • 發佈:2019-01-09
Web application conditions:@ConditionalOnWebApplication和@ConditionalOnNotWebApplication,當專案是web專案,或者不是web專案的條件註解
SpEL expression conditions:@ConditionalOnExpression,根據SPEL表示式執行結果作為條件
自動裝配程式碼跟蹤:
我們從上一章節的@SpringBootApplication開始,由於@SpringBootApplication是由@EnableAutoConfiguration組成的,我們觀察@EnableAutoConfiguration註解的原始碼如下:
- //
- // Source code recreated from a .class file by IntelliJ IDEA
- // (powered by Fernflower decompiler)
- //
- package org.springframework.boot.autoconfigure;
- import java.lang.annotation.Documented;
- import java.lang.annotation.ElementType;
- import java.lang.annotation.Inherited;
-
import
- import java.lang.annotation.RetentionPolicy;
- import java.lang.annotation.Target;
- import org.springframework.context.annotation.Import;
- @Target({ElementType.TYPE})
- @Retention(RetentionPolicy.RUNTIME)
- @Documented
- @Inherited
- @AutoConfigurationPackage
-
@Import
- public @interface EnableAutoConfiguration {
- String ENABLED_OVERRIDE_PROPERTY = "spring.boot.enableautoconfiguration";
- Class<?>[] exclude() default {};
- String[] excludeName() default {};
- }
EnableAutoConfiguration使用@Import註解將EnableAutoConfigurationImportSelector匯入並宣告為一個Bean,跟蹤EnableAutoConfigurationImportSelector的原始碼,發現其繼承AutoConfigurationImportSelector類,而其中有這麼一個方法getCandidateConfigurations
Java程式碼- protected List<String> getCandidateConfigurations(AnnotationMetadata metadata,AnnotationAttributes attributes) {
- List<String> configurations = SpringFactoriesLoader.loadFactoryNames(this.getSpringFactoriesLoaderFactoryClass(), this.getBeanClassLoader());
- //...省略其餘程式碼
- }
- public static List<String> loadFactoryNames(Class<?> factoryClass, ClassLoader classLoader) {
- String factoryClassName = factoryClass.getName();
- try {
- Enumeration<URL> urls = classLoader != null ? classLoader.getResources("META-INF/spring.factories") :ClassLoader.getSystemResources("META-INF/spring.factories");
- ArrayList result = new ArrayList();
- while(urls.hasMoreElements()) {
- URL url = (URL)urls.nextElement();
- Properties properties = PropertiesLoaderUtils.loadProperties(new UrlResource(url));
- String factoryClassNames = properties.getProperty(factoryClassName);
- result.addAll(Arrays.asList(StringUtils.commaDelimitedListToStringArray(factoryClassNames)));
- }
發現最終讀取的就是META-INF/spring.factories檔案,點選intellij中【External Libraries】中spring-boot-autoconfigure-1.5.7.RELEASE.jar,開啟META-INF/spring.factories檔案,檢視裡面內容