Spring Boot自動裝配原理和源碼分析

該篇的主要內容git

  1. Spring Boot的自動裝配原理【有案例模擬】
  2. Spring Boot自動裝配源碼分析

SpringBoot中的自動裝載原理

SpringBoot具有開箱即用的特色,它默默的幫咱們作了不少事情【自動建立和裝配不少對象】
程序員

自動裝配的實現

主要是經過ImportSelector接口完成的自動裝配
spring

ImportSelector

ImportSelector接口是Spring導入外部配置的核心接口,在SpringBoot的自動化配置和@EnableXXX(功能性註解)中起到了決定性的做用。當在@Configuration標註的Class上使用@Import引入了一個 ImportSelector實現類後,會把實現類中返回的Class名稱都定義爲bean。
編程

package org.springframework.context.annotation;

import org.springframework.core.type.AnnotationMetadata;

public interface ImportSelector {

	/**
	 * Select and return the names of which class(es) should be imported based on
	 * the {@link AnnotationMetadata} of the importing @{@link Configuration} class.
	 */
	String[] selectImports(AnnotationMetadata importingClassMetadata);

} 複製代碼

該接口的繼承關係圖
bash

在這裏插入圖片描述

DeferredImportSelector

由上圖可知DeferredImportSelector接口繼承自ImportSelector,它和ImportSelector的區別在於裝載bean的時機上,DeferredImportSelector須要等全部的@Configuration都執行完畢後纔會進行裝載
微信

Spring Boot自動裝配案例

項目案例傳送門:autoConfig
app

案例主要代碼

  1. 建立一個生產Bean的配置類,可是咱們並不使用@Configuration註解來聲明它。

public class MyConfig {
    @Bean(value = "chenfu", name = "chenfu")
    public Map<Object, Object> getMap() {
        HashMap<Object, Object> map = new HashMap<>();
        map.put("code", 200);
        map.put("msg", "success");
        String nowDate = LocalDateTime.now().format(DateTimeFormatter.ISO_LOCAL_DATE_TIME);
        map.put("data", nowDate);
        return map;
    }
} 複製代碼
2.實現ImportSelector接口,返回咱們上邊的配置類名

public class MyConfigImportSelector implements ImportSelector {
    @Override
    public String[] selectImports(AnnotationMetadata annotationMetadata) {
//        返回配置名稱
        return new String[]{MyConfig.class.getName()};
    }
} 複製代碼
3.運行測試

@SpringBootApplication
@Import(value = MyConfigImportSelector.class)
public class AutoConfigApp {
    public static void main(String[] args) {
        ConfigurableApplicationContext app = SpringApplication.run(AutoConfigApp.class, args);
        Object chenfu = app.getBean("chenfu");
        System.out.println(chenfu);
    }
} 

複製代碼

案例大致內容如上,經過案例可知通過Spring Boot自動裝配的對象並無使用Spring的對象建立註解聲明 (@Controller,@Service,@Repostiroty),而是使用編程的方式動態的載入bean。在Spring Boor中對這些對象的解析步驟主要是在ConfigurationClassParser類的processImports方法內進行的
ide

ImportSelector的解析過程

ConfigurationClassParser

ConfigurationClassParser類的源碼
源碼分析

private void processImports(ConfigurationClass configClass, SourceClass currentSourceClass,
		Collection<SourceClass> importCandidates, boolean checkForCircularImports) {
	if (importCandidates.isEmpty()) {
		return;
	}
	if (checkForCircularImports && isChainedImportOnStack(configClass)) {
		this.problemReporter.error(new CircularImportProblem(configClass, this.importStack));
	}
	else {
		this.importStack.push(configClass);
		try {
			for (SourceClass candidate : importCandidates) {
				//對ImportSelector類型的類進行處理
				if (candidate.isAssignable(ImportSelector.class)) {
					// Candidate class is an ImportSelector -> delegate to it to determine imports
					Class<?> candidateClass = candidate.loadClass();
					ImportSelector selector = BeanUtils.instantiateClass(candidateClass, ImportSelector.class);
					ParserStrategyUtils.invokeAwareMethods(
							selector, this.environment, this.resourceLoader, this.registry);
 					//上邊咱們說過的另一種Selector類型,能夠理解爲延遲加載
					if (selector instanceof DeferredImportSelector) {
						//該方法內部會將該Selector保存到一個集合【deferredImportSelectors】中
						this.deferredImportSelectorHandler.handle(
								configClass, (DeferredImportSelector) selector);
					} else {
						String[] importClassNames = selector.selectImports(currentSourceClass.getMetadata());
						Collection<SourceClass> importSourceClasses = asSourceClasses(importClassNames);
						processImports(configClass, currentSourceClass, importSourceClasses, 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 =
							BeanUtils.instantiateClass(candidateClass, ImportBeanDefinitionRegistrar.class);
					ParserStrategyUtils.invokeAwareMethods(
							registrar, 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
					// 直接把上邊的官方英文註釋硬翻譯了,當前類不是ImportSelector或ImportBeanDefinitionRegistrar類型,直接讓其走@Configuration類的處理流程
					this.importStack.registerImport(
							currentSourceClass.getMetadata(), candidate.getMetadata().getClassName());
					processConfigurationClass(candidate.asConfigClass(configClass));
				}
			}
		} catch (BeanDefinitionStoreException ex) {
			throw ex;
		} catch (Throwable ex) {
			throw new BeanDefinitionStoreException(
					"Failed to process import candidates for configuration class [" +
					configClass.getMetadata().getClassName() + "]", ex);
		} finally {
			this.importStack.pop();
		}
	}
} 

複製代碼

綜上,大體流程就是ImportSelector接口的返回值會遞歸進行解析,而後把解析到的類全名最終按照 @Configuration進行處理。
post

ImportSelector總結

SpringBoot開箱即用的特色,很大程度上歸功於ImportSelector。

Spring Boot源碼分析

Spring Boot在Spring的基礎上作了一些擴展。

  1. 在SpringBoot的SpringBootApplication註解中聲明瞭一個 @EnableAutoConfiguration註解

@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(
    excludeFilters = {@Filter(
    type = FilterType.CUSTOM,
    classes = {TypeExcludeFilter.class}
), @Filter(
    type = FilterType.CUSTOM,
    classes = {AutoConfigurationExcludeFilter.class}
)}
)
public @interface SpringBootApplication { 複製代碼
2.@EnableAutoConfiguration中經過Import引入了SpringBoot定義的@Import({AutoConfigurationImportSelector.class})

@Import({AutoConfigurationImportSelector.class})
public @interface EnableAutoConfiguration { 複製代碼

接下來開始對AutoConfigurationImportSelector進行源碼分析

AutoConfigurationImportSelector

AutoConfigurationImportSelector是selectImports的實現類,咱們來看selectImports方法

selectImports

public String[] selectImports(AnnotationMetadata annotationMetadata) {
    if (!this.isEnabled(annotationMetadata)) {
        return NO_IMPORTS;
    } else {
        AutoConfigurationMetadata autoConfigurationMetadata = AutoConfigurationMetadataLoader.loadMetadata(this.beanClassLoader);
        AutoConfigurationImportSelector.AutoConfigurationEntry autoConfigurationEntry = this.getAutoConfigurationEntry(autoConfigurationMetadata, annotationMetadata);
        return StringUtils.toStringArray(autoConfigurationEntry.getConfigurations());
    }
} 

複製代碼

該方法的主要邏輯都在getAutoConfigurationEntry方法內

getAutoConfigurationEntry

protected AutoConfigurationImportSelector.AutoConfigurationEntry getAutoConfigurationEntry(AutoConfigurationMetadata autoConfigurationMetadata, AnnotationMetadata annotationMetadata) {
    if (!this.isEnabled(annotationMetadata)) {
        return EMPTY_ENTRY;
    } else {
        AnnotationAttributes attributes = this.getAttributes(annotationMetadata);
        // 2.1經過getCandidateConfigurations方法獲取全部須要加載的bean
        List<String> configurations = this.getCandidateConfigurations(annotationMetadata, attributes);
        // 去重
        configurations = this.removeDuplicates(configurations);
        // 獲取不須要加載的bean,咱們能夠經過spring.autoconfigure.exclude配置
        Set<String> exclusions = this.getExclusions(annotationMetadata, attributes);
        this.checkExcludedClasses(configurations, exclusions);
        configurations.removeAll(exclusions);
        configurations = this.filter(configurations, autoConfigurationMetadata);
        // 發送事件,通知全部的AutoConfigurationImportListener進行監聽
        this.fireAutoConfigurationImportEvents(configurations, exclusions);
        return new AutoConfigurationImportSelector.AutoConfigurationEntry(configurations, exclusions);
    }
} 複製代碼

接下來再看一下上邊源碼中調用的getCandidateConfigurations方法

getCandidateConfigurations

protected List<String> getCandidateConfigurations(AnnotationMetadata metadata, AnnotationAttributes attributes) {
	// 這裏的getSpringFactoriesLoaderFactoryClass()最終返回的是EnableAutoConfiguration.class
    List<String> configurations = SpringFactoriesLoader.loadFactoryNames(this.getSpringFactoriesLoaderFactoryClass(), this.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;
} 

複製代碼

從上面的邏輯能夠看出,終獲取bean的渠道在SpringFactoriesLoader.loadFactoryNames內SpringFactoriesLoader.loadFactoryNames(this.getSpringFactoriesLoaderFactoryClass(), this.getBeanClassLoader());

SpringFactoriesLoader

loadFactoryNames

public static List<String> loadFactoryNames(Class<?> factoryClass, @Nullable ClassLoader classLoader) {
	// 經過factoryClassName獲取相應的bean全稱
    String factoryClassName = factoryClass.getName();
    return (List)loadSpringFactories(classLoader).getOrDefault(factoryClassName, Collections.emptyList());
} 

複製代碼

loadSpringFactories

private static Map<String, List<String>> loadSpringFactories(@Nullable ClassLoader classLoader) {
    MultiValueMap<String, String> result = (MultiValueMap)cache.get(classLoader);
    if (result != null) {
        return result;
    } else {
        try {
        	// 獲取項目中全部META-INF/spring.factories文件,將其組裝成Map
            Enumeration<URL> urls = classLoader != null ? classLoader.getResources("META-INF/spring.factories") : ClassLoader.getSystemResources("META-INF/spring.factories");
            LinkedMultiValueMap result = new LinkedMultiValueMap();

            while(urls.hasMoreElements()) {
                URL url = (URL)urls.nextElement();
                UrlResource resource = new UrlResource(url);
                Properties properties = PropertiesLoaderUtils.loadProperties(resource);
                Iterator var6 = properties.entrySet().iterator();

                while(var6.hasNext()) {
                    Entry<?, ?> entry = (Entry)var6.next();
                    String factoryClassName = ((String)entry.getKey()).trim();
                    String[] var9 = StringUtils.commaDelimitedListToStringArray((String)entry.getValue());
                    int var10 = var9.length;

                    for(int var11 = 0; var11 < var10; ++var11) {
                        String factoryName = var9[var11];
                        result.add(factoryClassName, factoryName.trim());
                    }
                }
            }

            cache.put(classLoader, result);
            return result;
        } catch (IOException var13) {
            throw new IllegalArgumentException("Unable to load factories from location [META-INF/spring.factories]", var13);
        }
    }
} 

複製代碼

每一個jar包均可以定義本身的META-INF/spring.factories,在該jar被加載的同時 spring.factories裏面定義的 bean就會被自動加載。咱們能夠來看一下Spring Boot的該配置文件內容【只拿出部份內容】

# Auto Configuration Import Filters
org.springframework.boot.autoconfigure.AutoConfigurationImportFilter=\
org.springframework.boot.autoconfigure.condition.OnBeanCondition,\
org.springframework.boot.autoconfigure.condition.OnClassCondition,\
org.springframework.boot.autoconfigure.condition.OnWebApplicationCondition

# 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,\ 複製代碼

故,咱們能夠對上邊的案例進行改造,在resouces目錄下建立該文件,而後添加以下內容

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
top.chenfu.auto.config.MyConfig   複製代碼

去掉啓動類中的@import或者自定義@EnableXXX註解

在這裏插入圖片描述

更多精彩文章,可關注微信公衆號:Java程序員彙集地

相關文章
相關標籤/搜索