您好,登錄后才能下訂單哦!
這篇文章主要介紹“SpringBoot啟動代碼和自動裝配源碼是什么”的相關知識,小編通過實際案例向大家展示操作過程,操作方法簡單快捷,實用性強,希望這篇“SpringBoot啟動代碼和自動裝配源碼是什么”文章能幫助大家解決問題。
隨著互聯網的快速發展,各種組件層出不窮,需要框架集成的組件越來越多。每一種組件與Spring容器整合需要實現相關代碼。SpringMVC框架配置由于太過于繁瑣和依賴XML文件;為了方便快速集成第三方組件和減少對配置文件的依賴,SpringBoot應運而生,其中采用了約定大于配置的理論讓開發者不需要過多配置即可進行開發。SpringBoot底層使用的Spring ,默認集成了N多組件的自動裝配。使用SpringBoot很簡單,在主類中添加一個@SpringBootApplication,以及調用SpringApplication.run()并傳入主類。代碼如下
@SpringBootApplication public class StartApp { public static void main(String[] args) { SpringApplication.run(StartApp.class); } }
由上面的源碼可知,SpringApplication.run()是SpringBoot的程序入口。本文會從SpringApplication.run()和@SpringBootApplication注解兩方面來分析。
SpringApplication.run(StartApp.class)的中關鍵代碼,先創建一個SpringApplication類,再執行run方法。代碼如下,
public static ConfigurableApplicationContext run(Class<?>[] primarySources, String[] args) { return new SpringApplication(primarySources).run(args); }
1.SpringApplication的構造方法代碼如下
public SpringApplication(ResourceLoader resourceLoader, Class<?>... primarySources) { // 設置資源加載器 this.resourceLoader = resourceLoader; Assert.notNull(primarySources, "PrimarySources must not be null"); // 設置應用主配置類 this.primarySources = new LinkedHashSet<>(Arrays.asList(primarySources)); // 獲取web服務器類型 this.webApplicationType = WebApplicationType.deduceFromClasspath(); // 從spring.factories 文件中獲取 ApplicationContextInitializer 的實現類 setInitializers((Collection) getSpringFactoriesInstances(ApplicationContextInitializer.class)); // 從spring.factories 文件中獲取 ApplicationListener 監聽器的實現類 setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class)); // 設置main啟動類 this.mainApplicationClass = deduceMainApplicationClass(); }
構造方法中主要邏輯:
1.設置應用主配置類,后面的run方法中會用它封裝成 BeanDefinitionHolder 并加載到 context 的 registry 中。
2.獲取web服務器類型,后面的run方法中會用它來創建具體的web服務類型。
3.從spring.factories 文件中獲取 ApplicationContextInitializer 的實現類,并設置給SpringApplication實例
4.從spring.factories 文件中獲取 ApplicationListener 監聽器的實現類,并設置給SpringApplication實例
5.設置main啟動類
其中getSpringFactoriesInstances方法主要邏輯是:從META-INF/spring.factories文件中根據接口獲取具體實現類字符串,并把字符串成實例化為對象。代碼如下,
// 獲取類加載器 ClassLoader classLoader = getClassLoader(); // Use names and ensure unique to protect against duplicates // 根據type 從META-INF/spring.factories獲取 具體的實現類字符串列表 Set<String> names = new LinkedHashSet<>(SpringFactoriesLoader.loadFactoryNames(type, classLoader)); // 實例化具體的實現類 List<T> instances = createSpringFactoriesInstances(type, parameterTypes, classLoader, args, names); // 排序 AnnotationAwareOrderComparator.sort(instances); return instances;
在META-INF/spring.factories文件中ApplicationContextInitializer.class 對應的實現類字符串為,
org.springframework.boot.context.ConfigurationWarningsApplicationContextInitializer,\ org.springframework.boot.context.ContextIdApplicationContextInitializer,\ org.springframework.boot.context.config.DelegatingApplicationContextInitializer,\ org.springframework.boot.rsocket.context.RSocketPortInfoApplicationContextInitializer,\ org.springframework.boot.web.context.ServerPortInfoApplicationContextInitializer
在META-INF/spring.factories文件中ApplicationListener.class 對應的實現類字符串為,
org.springframework.boot.ClearCachesApplicationListener,\ org.springframework.boot.builder.ParentContextCloserApplicationListener,\ org.springframework.boot.cloud.CloudFoundryVcapEnvironmentPostProcessor,\ org.springframework.boot.context.FileEncodingApplicationListener,\ org.springframework.boot.context.config.AnsiOutputApplicationListener,\ org.springframework.boot.context.config.ConfigFileApplicationListener,\ org.springframework.boot.context.config.DelegatingApplicationListener,\ org.springframework.boot.context.logging.ClasspathLoggingApplicationListener,\ org.springframework.boot.context.logging.LoggingApplicationListener,\ org.springframework.boot.liquibase.LiquibaseServiceLocatorApplicationListener
2.run方法的代碼如下,
StopWatch stopWatch = new StopWatch(); stopWatch.start(); ConfigurableApplicationContext context = null; Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList<>(); // 設置了一個名為 java.awt.headless 的系統屬性 // 其實是想設計應用程序,即使沒有檢測到顯示器,也允許其啟動 // 對于服務器來說,是不需要顯示器的 ,所以要這樣設置 configureHeadlessProperty(); // 獲取 SpringApplicationRunListener 加載的是 EventPublishingRunListener // 獲取啟動時的監聽器 SpringApplicationRunListeners listeners = getRunListeners(args); // 觸發啟動事件 listeners.starting(); try { // 構造一個應用程序的參數持有類 ApplicationArguments applicationArguments = new DefaultApplicationArguments(args); // 創建并配置環境 ConfigurableEnvironment environment = prepareEnvironment(listeners, applicationArguments); // 配置需要忽略的BeanInfo信息 configureIgnoreBeanInfo(environment); Banner printedBanner = printBanner(environment); // 創建上下文對象 context = createApplicationContext(); // 加載配置的啟動異常處理器 exceptionReporters = getSpringFactoriesInstances(SpringBootExceptionReporter.class, new Class[] { ConfigurableApplicationContext.class }, context); // 刷新前操作 prepareContext(context, environment, listeners, applicationArguments, printedBanner); // 刷新應用上下文 完成 Spring 容器的初始化 refreshContext(context); // 刷新后操作 afterRefresh(context, applicationArguments); stopWatch.stop(); if (this.logStartupInfo) { new StartupInfoLogger(this.mainApplicationClass).logStarted(getApplicationLog(), stopWatch); } // 啟動完成事件 listeners.started(context); // 執行 ApplicationRunner 和 CommandLineRunner 實現類 callRunners(context, applicationArguments); } catch (Throwable ex) { // 事件廣播啟動出錯了 handleRunFailure(context, ex, exceptionReporters, listeners); throw new IllegalStateException(ex); } try { // 運行事件 listeners.running(context); } catch (Throwable ex) { handleRunFailure(context, ex, exceptionReporters, null); throw new IllegalStateException(ex); } return context;
run方法中主要邏輯:
1. 從spring.factories 文件中獲取 SpringApplicationRunListener 的實現類(監聽事件發布器),并在context生命周期中執行相關的事件 ,比如觸發啟動事件、啟動完成事件等。
2.創建Web應用上下文對象,根據webApplicationType來創建具體的web服務類型。
3.刷新前操作,把主配置類資源封裝成 BeanDefinitionHolder 加載到 context 的 registry 中。
4.刷新應用上下文 完成 Spring 容器的初始化。
5.執行 實現了 ApplicationRunner 和 CommandLineRunner 接口的類。
@SpringBootApplication注解其中主要是利用@Import 注解,@Import源碼如下:
@Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface Import { /** * {@link Configuration @Configuration}, {@link ImportSelector}, * {@link ImportBeanDefinitionRegistrar}, or regular component classes to import. */ Class<?>[] value(); }
@Import在注解一般和@Configuration一起用,Spring容器初始化的過程中會進行解析@Configuration注解類(源碼在org.springframework.context.annotation.ConfigurationClassPostProcessor#processConfigBeanDefinitions中),其過程會解析注解類的@Import注解的元數據,并根據類是否實現相關接口進行處理。源碼位置:org.springframework.context.annotation.ConfigurationClassParser#processImports;關鍵代碼如下,
try { for (SourceClass candidate : importCandidates) { if (candidate.isAssignable(ImportSelector.class)) { // Candidate class is an ImportSelector -> delegate to it to determine imports Class<?> candidateClass = candidate.loadClass(); ImportSelector selector = ParserStrategyUtils.instantiateClass(candidateClass, ImportSelector.class, this.environment, this.resourceLoader, this.registry); Predicate<String> selectorFilter = selector.getExclusionFilter(); if (selectorFilter != null) { exclusionFilter = exclusionFilter.or(selectorFilter); } if (selector instanceof DeferredImportSelector) { this.deferredImportSelectorHandler.handle(configClass, (DeferredImportSelector) selector); } else { String[] importClassNames = selector.selectImports(currentSourceClass.getMetadata()); Collection<SourceClass> importSourceClasses = asSourceClasses(importClassNames, exclusionFilter); processImports(configClass, currentSourceClass, importSourceClasses, exclusionFilter, false); } } else if (candidate.isAssignable(ImportBeanDefinitionRegistrar.class)) { // Candidate class is an ImportBeanDefinitionRegistrar -> // delegate to it to register additional bean definitions Class<?> candidateClass = candidate.loadClass(); ImportBeanDefinitionRegistrar registrar = ParserStrategyUtils.instantiateClass(candidateClass, ImportBeanDefinitionRegistrar.class, this.environment, this.resourceLoader, this.registry); configClass.addImportBeanDefinitionRegistrar(registrar, currentSourceClass.getMetadata()); } else { // Candidate class not an ImportSelector or ImportBeanDefinitionRegistrar -> // process it as an @Configuration class this.importStack.registerImport( currentSourceClass.getMetadata(), candidate.getMetadata().getClassName()); processConfigurationClass(candidate.asConfigClass(configClass), exclusionFilter); } } }
從上面代碼可知@Import的value類使用有三種場景:
1.實現了 ImportSelector.class接口的場景;直接調用實例selector 的selectImports方法返回要實例化的Bean對象的全類名列表,并根據全類名字符串列表創建實例對象,然后遞歸調用當前的processImports 方法,最終會添加到configurationClasses的集合中,configurationClasses集合中的對象會被注冊到BeanDefinitionRegistry類型的 registry 對象中。實現接口ImportSelector這種情況下又擴展了 DeferredImportSelector 接口的情況,該接口用來實現BeanDefinition的延遲注入功能更。DeferredImportSelector接口擴展了ImportSelector接口,并且其中有個內部接口 Group,如果某個@Import注解的value類實現了DeferredImportSelector接口并且也實現了該接口的內部類Group接口,則表面此實現類需要延遲處理。如果是需要延遲處理,則會把ImportSelector 實例selector 組裝成 DeferredImportSelectorHolder 對象添加到 deferredImportSelectors集合中,處理邏輯源碼位置: org.springframework.context.annotation.ConfigurationClassParser.DeferredImportSelectorHandler#handle;關鍵代碼如下,
public void handle(ConfigurationClass configClass, DeferredImportSelector importSelector) { DeferredImportSelectorHolder holder = new DeferredImportSelectorHolder(configClass, importSelector); if (this.deferredImportSelectors == null) { DeferredImportSelectorGroupingHandler handler = new DeferredImportSelectorGroupingHandler(); handler.register(holder); handler.processGroupImports(); } else { this.deferredImportSelectors.add(holder); } }
DeferredImportSelector接口的實現邏輯會在org.springframework.context.annotation.ConfigurationClassParser#parse方法中調用,具體代碼在this.deferredImportSelectorHandler.process()中,關鍵代碼如下,
public void process() { List<DeferredImportSelectorHolder> deferredImports = this.deferredImportSelectors; this.deferredImportSelectors = null; try { if (deferredImports != null) { DeferredImportSelectorGroupingHandler handler = new DeferredImportSelectorGroupingHandler(); deferredImports.sort(DEFERRED_IMPORT_COMPARATOR); deferredImports.forEach(handler::register); // 具體的執行邏輯 handler.processGroupImports(); } } finally { this.deferredImportSelectors = new ArrayList<>(); } }
在processGroupImports()方法中,先通過grouping.getImports()拿到需要自動裝配的Group.Entry(封裝了全類名)對象集合,然后通過processImports()方法根據Entry類名字符串進行創建SourceClass類(該類可以通過asConfigClass()方法轉成ConfigurationClass對象),最終添加到configurationClasses集合中。代碼如下,
public void processGroupImports() { for (DeferredImportSelectorGrouping grouping : this.groupings.values()) { Predicate<String> exclusionFilter = grouping.getCandidateFilter(); grouping.getImports().forEach(entry -> { ConfigurationClass configurationClass = this.configurationClasses.get(entry.getMetadata()); try { processImports(configurationClass, asSourceClass(configurationClass, exclusionFilter), Collections.singleton(asSourceClass(entry.getImportClassName(), exclusionFilter)), exclusionFilter, false); } catch (BeanDefinitionStoreException ex) { throw ex; } catch (Throwable ex) { throw new BeanDefinitionStoreException( "Failed to process import candidates for configuration class [" + configurationClass.getMetadata().getClassName() + "]", ex); } }); } }
grouping.getImports()方法中主要執行具體的實現類的process方法和selectImports()方法(如果是AutoConfigurationImportSelector類,則調用org.springframework.boot.autoconfigure.AutoConfigurationImportSelector.AutoConfigurationGroup#process和org.springframework.boot.autoconfigure.AutoConfigurationImportSelector.AutoConfigurationGroup#selectImports,兩個方法的具體類容請看2.2.2章節的說明),selectImports返回需要自動裝配的Group.Entry對象集合,Entry對象中保存了全類名。代碼如下:
public Iterable<Group.Entry> getImports() { for (DeferredImportSelectorHolder deferredImport : this.deferredImports) { this.group.process(deferredImport.getConfigurationClass().getMetadata(), deferredImport.getImportSelector()); } return this.group.selectImports(); }
ImportSelector接口代碼代碼如下:
public interface ImportSelector { String[] selectImports(AnnotationMetadata importingClassMetadata); @Nullable default Predicate<String> getExclusionFilter() { return null; } }
DeferredImportSelector接口的代碼如下:
public interface DeferredImportSelector extends ImportSelector { @Nullable default Class<? extends Group> getImportGroup() { return null; } interface Group { void process(AnnotationMetadata metadata, DeferredImportSelector selector); Iterable<Entry> selectImports(); class Entry { // 省略 } } }
2.實現了 ImportBeanDefinitionRegistrar.class接口的場景;會先創建ImportBeanDefinitionRegistrar 實例類 registrar,再把 registrar 添加到 configClass 的 importBeanDefinitionRegistrars中,接口的registerBeanDefinitions方法的調用是在 org.springframework.context.annotation.ConfigurationClassPostProcessor#processConfigBeanDefinitions方法里的this.reader.loadBeanDefinitions(configClasses)代碼中。具體執行語句loadBeanDefinitionsFromRegistrars(configClass.getImportBeanDefinitionRegistrars());關鍵代碼如下,
private void loadBeanDefinitionsFromRegistrars(Map<ImportBeanDefinitionRegistrar, AnnotationMetadata> registrars) { registrars.forEach((registrar, metadata) -> registrar.registerBeanDefinitions(metadata, this.registry, this.importBeanNameGenerator)); }
ImportBeanDefinitionRegistrar接口代碼如下:
public interface ImportBeanDefinitionRegistrar { default void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry, BeanNameGenerator importBeanNameGenerator) { registerBeanDefinitions(importingClassMetadata, registry); } default void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) { } }
3.沒有實現以上兩接口的普通類,會直接調用org.springframework.context.annotation.ConfigurationClassParser#processImports里面的processConfigurationClass方法,把當前configClass添加至 configurationClasses 集合中。configurationClasses集合中的對象最終會被注冊到BeanDefinitionRegistry類型的 registry 對象中。
@SpringApplication注解主要包括了@SpringBootConfiguration、@EnableAutoConfiguration、@ComponentScan。代碼如下,
@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) })
配置注解,包含了@Configuration注解,表明是配置類。
自動裝配注解,主要邏輯是:根據 EnableAutoConfiguration 類型從META-INF/spring.factories 文件加載需要自動裝配的類,并注入到Spring容器中。它包括了@AutoConfigurationPackage注解和一個@Import(AutoConfigurationImportSelector.class)注解。代碼如下,
@Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented @Inherited @AutoConfigurationPackage @Import(AutoConfigurationImportSelector.class)
注冊名為 org.springframework.boot.autoconfigure.AutoConfigurationPackages ,BeanClass為BasePackages.class 的GenericBeanDefinition 到 BeanDefinitionRegistry 中,通過@Import 注解實現注入功能,代碼如下,
@Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented @Inherited @Import(AutoConfigurationPackages.Registrar.class) public @interface AutoConfigurationPackage { }
AutoConfigurationPackages.Registrar.class實現了ImportBeanDefinitionRegistrar接口 ,所以在Spring容器初始化的過程中會調用它的registerBeanDefinitions方法把PackageImport類注入到Spring容器中去。代碼如下,
static class Registrar implements ImportBeanDefinitionRegistrar, DeterminableImports { @Override public void registerBeanDefinitions(AnnotationMetadata metadata, BeanDefinitionRegistry registry) { register(registry, new PackageImport(metadata).getPackageName()); } @Override public Set<Object> determineImports(AnnotationMetadata metadata) { return Collections.singleton(new PackageImport(metadata)); } }
自動裝配關鍵邏輯,先從META-INF/spring.factories 文件加載類型值為 EnableAutoConfiguration的字符串集合,再通過過濾,生成需要自動裝配的類,最后注入到Spring容器中。AutoConfigurationImportSelector實現了DeferredImportSelector接口并且內部也實現了DeferredImportSelector.Group接口,所以在Spring容器初始化的過程中會調用
org.springframework.boot.autoconfigure.AutoConfigurationImportSelector.AutoConfigurationGroup#process方法和#selectImports方法,
process()用來生成需要自動裝配的類型,方法的代碼如下,
Assert.state(deferredImportSelector instanceof AutoConfigurationImportSelector, () -> String.format("Only %s implementations are supported, got %s", AutoConfigurationImportSelector.class.getSimpleName(), deferredImportSelector.getClass().getName())); // 1. getAutoConfigurationMetadata() // 從META-INF/spring-autoconfigure-metadata.properties文件中獲取自動裝配的元數據, // 里面保存了加載類是否自動裝配的條件 , // org.springframework.boot.autoconfigure.jms.JmsAutoConfiguration.ConditionalOnBean // =javax.jms.ConnectionFactory // 2. getAutoConfigurationEntry() // 從 META-INF/spring.factories 文件中獲取key為 EnableAutoConfiguration 的配置類字符串類表 并封裝成 自動裝配類對象 AutoConfigurationEntry autoConfigurationEntry = ((AutoConfigurationImportSelector) deferredImportSelector) .getAutoConfigurationEntry(getAutoConfigurationMetadata(), annotationMetadata); this.autoConfigurationEntries.add(autoConfigurationEntry); // 循環遍歷 自動裝配類對象 的自動裝配類字符串 ,添加到 this.entries for (String importClassName : autoConfigurationEntry.getConfigurations()) { this.entries.putIfAbsent(importClassName, annotationMetadata); }
getAutoConfigurationMetadata() 方法主要邏輯是:從META-INF/spring-autoconfigure-metadata.properties文件中獲取自動裝配的元數據,里面保存了自動加載類是否符合自動裝配的前置條件,比較熟悉的有ConditionalOnClass和ConditionalOnBean,文件相關內容如下:
org.springframework.boot.autoconfigure.data.jpa.JpaRepositoriesAutoConfiguration= org.springframework.boot.autoconfigure.web.client.RestTemplateAutoConfiguration.AutoConfigureAfter=org.springframework.boot.autoconfigure.http.HttpMessageConvertersAutoConfiguration org.springframework.boot.autoconfigure.data.cassandra.CassandraReactiveDataAutoConfiguration.ConditionalOnClass=com.datastax.driver.core.Cluster,reactor.core.publisher.Flux,org.springframework.data.cassandra.core.ReactiveCassandraTemplate org.springframework.boot.autoconfigure.data.solr.SolrRepositoriesAutoConfiguration.ConditionalOnClass=org.apache.solr.client.solrj.SolrClient,org.springframework.data.solr.repository.SolrRepository org.springframework.boot.autoconfigure.security.oauth3.client.servlet.OAuth3ClientAutoConfiguration.ConditionalOnWebApplication=SERVLET org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration= org.springframework.boot.autoconfigure.jersey.JerseyAutoConfiguration.AutoConfigureBefore=org.springframework.boot.autoconfigure.web.servlet.DispatcherServletAutoConfiguration org.springframework.boot.autoconfigure.jms.artemis.ArtemisXAConnectionFactoryConfiguration= org.springframework.boot.autoconfigure.web.reactive.HttpHandlerAutoConfiguration.ConditionalOnWebApplication=REACTIVE org.springframework.boot.autoconfigure.web.reactive.ReactiveWebServerFactoryAutoConfiguration.ConditionalOnWebApplication=REACTIVE org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchRepositoriesAutoConfiguration= org.springframework.boot.autoconfigure.security.oauth3.resource.servlet.OAuth3ResourceServerAutoConfiguration.ConditionalOnWebApplication=SERVLET org.springframework.boot.autoconfigure.web.servlet.MultipartAutoConfiguration.ConditionalOnWebApplication=SERVLET //省略
getAutoConfigurationEntry()方法 主要邏輯是:從spring.factories 文件中獲取key為 EnableAutoConfiguration 的配置類字符串列表并封裝成自動裝配類AutoConfigurationEntry對象,代碼如下,
protected AutoConfigurationEntry getAutoConfigurationEntry(AutoConfigurationMetadata autoConfigurationMetadata, AnnotationMetadata annotationMetadata) { if (!isEnabled(annotationMetadata)) { return EMPTY_ENTRY; } // 獲取注解元數據的屬性 AnnotationAttributes attributes = getAttributes(annotationMetadata); // 從spring.factories 文件中獲取key為 EnableAutoConfiguration 的配置類字符串列表 List<String> configurations = getCandidateConfigurations(annotationMetadata, attributes); // 去掉重復的 自動裝配類字符串 configurations = removeDuplicates(configurations); // 根據注解元數據獲取 需要排除的類名 Set<String> exclusions = getExclusions(annotationMetadata, attributes); // 檢查排除的類名 checkExcludedClasses(configurations, exclusions); // 根據排除的類名進行排除 configurations.removeAll(exclusions); // 從spring.factories 文件中獲取key為 AutoConfigurationImportFilter 的配置對象進行過濾 // 過濾規則從 getAutoConfigurationMetadata() 返回類的數據中獲取 configurations = filter(configurations, autoConfigurationMetadata); // 執行導入配置類的監聽事件 fireAutoConfigurationImportEvents(configurations, exclusions); // 返回 AutoConfigurationEntry 對象 return new AutoConfigurationEntry(configurations, exclusions); }
getCandidateConfigurations()方法從spring.factories 文件中獲取類型為 EnableAutoConfiguration 的配置類字符串列表,代碼如下,
// getSpringFactoriesLoaderFactoryClass()方法返回 EnableAutoConfiguration List<String> configurations = SpringFactoriesLoader.loadFactoryNames(getSpringFactoriesLoaderFactoryClass(), getBeanClassLoader()); Assert.notEmpty(configurations, "No auto configuration classes found in META-INF/spring.factories. If you " + "are using a custom packaging, make sure that file is correct."); return configurations;
在META-INF/spring.factories文件中EnableAutoConfiguration .class 對應的實現類字符串為
# Auto Configure 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,\ // 省略
2.selectImports()方法返回排序后的 Entry(需要自動裝配的包裝實體類) 對象集合,代碼如下,
public Iterable<Entry> selectImports() { if (this.autoConfigurationEntries.isEmpty()) { return Collections.emptyList(); } Set<String> allExclusions = this.autoConfigurationEntries.stream() .map(AutoConfigurationEntry::getExclusions).flatMap(Collection::stream).collect(Collectors.toSet()); Set<String> processedConfigurations = this.autoConfigurationEntries.stream() .map(AutoConfigurationEntry::getConfigurations).flatMap(Collection::stream) .collect(Collectors.toCollection(LinkedHashSet::new)); processedConfigurations.removeAll(allExclusions); // 返回排序后的 Entry 集合 return sortAutoConfigurations(processedConfigurations, getAutoConfigurationMetadata()).stream() .map((importClassName) -> new Entry(this.entries.get(importClassName), importClassName)) .collect(Collectors.toList()); }
注意:@EnableAutoConfiguration 注解的分析過程需要結合@Import注解的過程來看。
組件掃描注解,用來配置自動掃描包路徑。如果沒有配置路徑,則掃描主配置類命名空間下的所有包和類。
關于“SpringBoot啟動代碼和自動裝配源碼是什么”的內容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業相關的知識,可以關注億速云行業資訊頻道,小編每天都會為大家更新不同的知識點。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。