SpringBoot自动装配源码分析

结论

SpringBoot程序启动类上的@SpringBootApplication注解由@SpringBootConfiguration、@EnableAutoConfiguration、@ComponentScan三个注解组成;@EnableAutoConfiguration注解使用@Import注解导入AutoConfigurationImportSelector类,该类使用SpringFactoriesLoader类加载classpath下META-INF/spring.factories文件中EnableAutoConfiguration属性定义的一系列自动装配类,结合@Conditional注解实现按需加载;这些自动装配类在SpringBoot程序启动时被ConfigurationClassPostProcessor(BeanFactoryPostProcessor类型)后置处理器解析,得到一系列的BeanDefination类装载到Spring容器中。

ApplicationContext和ConfigurationClassPostProcessor

ApplicationContext是Spring的基础容器,在SpringBoot中ApplicationContext是在SpringApplication.run(String... args)方法中创建的。

public ConfigurableApplicationContext run(String... args) {
		long startTime = System.nanoTime();
		DefaultBootstrapContext bootstrapContext = createBootstrapContext();
		ConfigurableApplicationContext context = null;
		//...
		try {
			ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);
			ConfigurableEnvironment environment = prepareEnvironment(listeners, bootstrapContext, applicationArguments);
			configureIgnoreBeanInfo(environment);
			Banner printedBanner = printBanner(environment);
            //创建ApplicationContext
			context = createApplicationContext();
			context.setApplicationStartup(this.applicationStartup);
			prepareContext(bootstrapContext, context, environment, listeners, applicationArguments, printedBanner);
			refreshContext(context);
			afterRefresh(context, applicationArguments);
			//...
		}
		catch (Throwable ex) {
			handleRunFailure(context, ex, listeners);
			throw new IllegalStateException(ex);
		}
		
		return context;
	}

进入ceateApplicationContext()方法

public class SpringApplication {
    //工厂类Factory,负责具体创建ApplicationContext
    private ApplicationContextFactory applicationContextFactory = ApplicationContextFactory.DEFAULT;
    //...
    protected ConfigurableApplicationContext createApplicationContext() {
        //ApplicationContextFactory.DEFAULT  = new DefaultApplicationContextFactory();
		return this.applicationContextFactory.create(this.webApplicationType);
	}
}

进入DefaultApplicationContextFactory.create方法

class DefaultApplicationContextFactory implements ApplicationContextFactory {
    @Override
	public ConfigurableApplicationContext create(WebApplicationType webApplicationType) {
		try {
            /*从clasapath:META-INFO/spring.factories中获取候选的ApplicationContextFactory列表
             *遍历ApplicationContextFactory,检测ApplicationContext类型是否与应用程序匹配
             */
			return getFromSpringFactories(webApplicationType, ApplicationContextFactory::create,
					AnnotationConfigApplicationContext::new);
		}
		catch (Exception ex) {
			throw new IllegalStateException("Unable create a default ApplicationContext instance, "
					+ "you may need a custom ApplicationContextFactory", ex);
		}
	}

    private <T> T getFromSpringFactories(WebApplicationType webApplicationType,
			BiFunction<ApplicationContextFactory, WebApplicationType, T> action, Supplier<T> defaultResult) {
        //候选ApplicationContextFactory分为两种
        //1.响应式spring-webflux AnnotationConfigReactiveWebServerApplicationContext.Factory
        //2.传统servlet spring-web AnnotationConfigServletWebServerApplicationContext.Factory    
		for (ApplicationContextFactory candidate : SpringFactoriesLoader.loadFactories(ApplicationContextFactory.class,
				getClass().getClassLoader())) {
			T result = action.apply(candidate, webApplicationType);
			if (result != null) {
				return result;
			}
		}
		return (defaultResult != null) ? defaultResult.get() : null;
	}
}

对于传统Servlet类型Spring Boot程序,最终实例化的ApplicationContext是AnnotationConfigServletWebServerApplicationContext,其构造函数如下:

public class AnnotationConfigServletWebServerApplicationContext extends ServletWebServerApplicationContext
		implements AnnotationConfigRegistry {

	private final AnnotatedBeanDefinitionReader reader;

	private final ClassPathBeanDefinitionScanner scanner;

    //...
    
	/**
	 * Create a new {@link AnnotationConfigServletWebServerApplicationContext} that needs
	 * to be populated through {@link #register} calls and then manually
	 * {@linkplain #refresh refreshed}.
	 */
	public AnnotationConfigServletWebServerApplicationContext() {
        //基于注解的BeanDefinition读取器
		this.reader = new AnnotatedBeanDefinitionReader(this);
        //基于类路径扫描的BeanDefinition读取器
		this.scanner = new ClassPathBeanDefinitionScanner(this);
	}
    //...
}

AnnotatedBeanDefinitionReader的构造函数向ApplicationContext中注入BeanFactoryPostProcessor后置处理器ConfigurationClassPostProcessor

public AnnotatedBeanDefinitionReader(BeanDefinitionRegistry registry, Environment environment) {
		Assert.notNull(registry, "BeanDefinitionRegistry must not be null");
		Assert.notNull(environment, "Environment must not be null");
		this.registry = registry;
		this.conditionEvaluator = new ConditionEvaluator(registry, environment, null);
        //注册ConfigurationClassPostProcessor后置处理器
		AnnotationConfigUtils.registerAnnotationConfigProcessors(this.registry);
	}

进入AnnotationConfigUtils.registerAnnotationConfigProcessors

public static Set<BeanDefinitionHolder> registerAnnotationConfigProcessors(
			BeanDefinitionRegistry registry, @Nullable Object source) {

		DefaultListableBeanFactory beanFactory = unwrapDefaultListableBeanFactory(registry);
		if (beanFactory != null) {
			if (!(beanFactory.getDependencyComparator() instanceof AnnotationAwareOrderComparator)) {
				beanFactory.setDependencyComparator(AnnotationAwareOrderComparator.INSTANCE);
			}
			if (!(beanFactory.getAutowireCandidateResolver() instanceof ContextAnnotationAutowireCandidateResolver)) {
				beanFactory.setAutowireCandidateResolver(new ContextAnnotationAutowireCandidateResolver());
			}
		}

		Set<BeanDefinitionHolder> beanDefs = new LinkedHashSet<>(8);
        // internalConfigurationAnnotationProcessor,用于处理@Configuration
		if (!registry.containsBeanDefinition(CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME)) {
			RootBeanDefinition def = new RootBeanDefinition(ConfigurationClassPostProcessor.class);
			def.setSource(source);
			beanDefs.add(registerPostProcessor(registry, def, CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME));
		}
    //....

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值