Spring源码分析之AnnotationConfigApplicationContext

AnnotationConfigApplicationContext

spring版本:5.2.8.RELEASE

全类名:org.springframework.context.annotation.AnnotationConfigApplicationContext
在这里插入图片描述

从类依赖图,我们可以看出AnnotationConfigApplicationContext实现了Bean定义的注册、Bean的实例化、事件、生命周期、国际化等功能。

今天我们不去分析这些功能的实现方式,我们从new AnnotationConfigApplicationContext(configClass)开始

AnnotationConfigApplicationContext annotationConfigApplicationContext = new AnnotationConfigApplicationContext(DemoConfig.class);

DemoConfig.class 是项目下的一个配置类

package com.mytest.spring;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@ComponentScan("com.mytest.spring")
@Configuration
public class DemoConfig {
}

构造方法

AnnotationConfigApplicationContext(Class<?>… componentClasses)

/**
	 * Create a new AnnotationConfigApplicationContext, deriving bean definitions
	 * from the given component classes and automatically refreshing the context.
	 * @param componentClasses one or more component classes &mdash; for example,
	 * {@link Configuration @Configuration} classes
	 */
	public AnnotationConfigApplicationContext(Class<?>... componentClasses) {
		this();
		register(componentClasses);
		refresh();
	}

看注释大概意思是:创建一个新的AnnotationConfigApplicationContext,从配置文件中提取Bean定义,自动刷新上下文。

Bean定义,好比是一个模型或图纸,有了图纸才能建各种不同的的房子、车子。有Bean定义,才可以进行创建不同类型的Bean对象,比如懒加载、单例等类型。

this()

This方法会创建两个对象,一个reader,一个scanner。

public AnnotationConfigApplicationContext() {
		this.reader = new AnnotatedBeanDefinitionReader(this);
		this.scanner = new ClassPathBeanDefinitionScanner(this);
	}

scanner,主要是为了方便在创建完AnnotationConfigApplicationContext对象时手动进行scan,比如:

AnnotationConfigApplicationContext annotationConfigApplicationContext = new AnnotationConfigApplicationContext(DemoConfig.class);
annotationConfigApplicationContext.scan("com.mytest.spring");

reader,重点关注

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);
		AnnotationConfigUtils.registerAnnotationConfigProcessors(this.registry);
	}

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);

		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));
		}

		if (!registry.containsBeanDefinition(AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME)) {
			RootBeanDefinition def = new RootBeanDefinition(AutowiredAnnotationBeanPostProcessor.class);
			def.setSource(source);
			beanDefs.add(registerPostProcessor(registry, def, AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME));
		}

		// Check for JSR-250 support, and if present add the CommonAnnotationBeanPostProcessor.
		if (jsr250Present && !registry.containsBeanDefinition(COMMON_ANNOTATION_PROCESSOR_BEAN_NAME)) {
			RootBeanDefinition def = new RootBeanDefinition(CommonAnnotationBeanPostProcessor.class);
			def.setSource(source);
			beanDefs.add(registerPostProcessor(registry, def, COMMON_ANNOTATION_PROCESSOR_BEAN_NAME));
		}

		// Check for JPA support, and if present add the PersistenceAnnotationBeanPostProcessor.
		if (jpaPresent && !registry.containsBeanDefinition(PERSISTENCE_ANNOTATION_PROCESSOR_BEAN_NAME)) {
			RootBeanDefinition def = new RootBeanDefinition();
			try {
				def.setBeanClass(ClassUtils.forName(PERSISTENCE_ANNOTATION_PROCESSOR_CLASS_NAME,
						AnnotationConfigUtils.class.getClassLoader()));
			}
			catch (ClassNotFoundException ex) {
				throw new IllegalStateException(
						"Cannot load optional framework class: " + PERSISTENCE_ANNOTATION_PROCESSOR_CLASS_NAME, ex);
			}
			def.setSource(source);
			beanDefs.add(registerPostProcessor(registry, def, PERSISTENCE_ANNOTATION_PROCESSOR_BEAN_NAME));
		}

		if (!registry.containsBeanDefinition(EVENT_LISTENER_PROCESSOR_BEAN_NAME)) {
			RootBeanDefinition def = new RootBeanDefinition(EventListenerMethodProcessor.class);
			def.setSource(source);
			beanDefs.add(registerPostProcessor(registry, def, EVENT_LISTENER_PROCESSOR_BEAN_NAME));
		}

		if (!registry.containsBeanDefinition(EVENT_LISTENER_FACTORY_BEAN_NAME)) {
			RootBeanDefinition def = new RootBeanDefinition(DefaultEventListenerFactory.class);
			def.setSource(source);
			beanDefs.add(registerPostProcessor(registry, def, EVENT_LISTENER_FACTORY_BEAN_NAME));
		}

		return beanDefs;
	}

这里注册了6个BeanDefinition,分别会处理不同的注解
image-20220423174419782

register(componentClasses)

该方法主要把配置类注册为BeanDefinition

refresh()

加载配置,扫描类,实例化非懒加载类都是在这里处理

@Override
	public void refresh() throws BeansException, IllegalStateException {
		synchronized (this.startupShutdownMonitor) {
			// Prepare this context for refreshing.
			prepareRefresh();

			// Tell the subclass to refresh the internal bean factory.
			ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

			// Prepare the bean factory for use in this context.
			prepareBeanFactory(beanFactory);

			try {
				// Allows post-processing of the bean factory in context subclasses.
				postProcessBeanFactory(beanFactory);

				// Invoke factory processors registered as beans in the context.
				invokeBeanFactoryPostProcessors(beanFactory);

				// Register bean processors that intercept bean creation.
				registerBeanPostProcessors(beanFactory);

				// Initialize message source for this context.
				initMessageSource();

				// Initialize event multicaster for this context.
				initApplicationEventMulticaster();

				// Initialize other special beans in specific context subclasses.
				onRefresh();

				// Check for listener beans and register them.
				registerListeners();

				// Instantiate all remaining (non-lazy-init) singletons.
				finishBeanFactoryInitialization(beanFactory);

				// Last step: publish corresponding event.
				finishRefresh();
			}

			catch (BeansException ex) {
				if (logger.isWarnEnabled()) {
					logger.warn("Exception encountered during context initialization - " +
							"cancelling refresh attempt: " + ex);
				}

				// Destroy already created singletons to avoid dangling resources.
				destroyBeans();

				// Reset 'active' flag.
				cancelRefresh(ex);

				// Propagate exception to caller.
				throw ex;
			}

			finally {
				// Reset common introspection caches in Spring's core, since we
				// might not ever need metadata for singleton beans anymore...
				resetCommonCaches();
			}
		}
	}

该方法执行逻辑下一次再分享

  • 9
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring框架是一个开源的Java应用程序框架,用于构建企业级应用程序。它提供了一种轻量级的、非侵入式的方式来管理Java对象的生命周期和依赖关系,从而简化了应用程序的开发和维护过程。下面是对Spring框架源码的简要讲解: 1. 核心容器(Core Container):Spring框架的核心是其IoC容器(Inversion of Control)。它通过IoC容器来管理和组织应用程序中的Bean对象。在IoC容器中,Spring使用`BeanFactory`接口和其实现类`DefaultListableBeanFactory`来加载、配置和管理Bean对象。 2. 上下文(Context):Spring还提供了更高级的上下文功能,如`ApplicationContext`接口和其实现类`AnnotationConfigApplicationContext`、`XmlWebApplicationContext`等。上下文扩展了`BeanFactory`的功能,提供了更多的企业级特性,如国际化、事件传播、资源加载等。 3. AOP(Aspect-Oriented Programming):Spring框架实现了AOP的支持,用于将横切关注点(cross-cutting concerns)从核心业务逻辑中分离出来。Spring AOP基于代理模式和动态代理技术,通过面向切面编程来实现横切关注点的模块化。 4. 数据访问(Data Access):Spring框架提供了对各种数据访问技术的支持,包括JDBC、ORM(如Hibernate、MyBatis)和事务管理。它通过抽象出数据访问层的公共接口,使得应用程序可以更容易地切换和集成不同的数据访问技术。 5. Web支持:Spring框架还提供了对Web应用程序开发的支持,包括Web MVC、RESTful服务、WebSocket等。它通过`DispatcherServlet`和一系列的处理器(Handler)来处理Web请求,并提供了一套强大的机制来实现灵活的Web应用程序开发。 6. 测试支持:Spring框架还提供了对单元测试和集成测试的支持,如`JUnit`和`TestNG`的集成、模拟对象(Mock Objects)的支持等。这使得开发人员可以更方便地编写和执行各种测试用例。 需要注意的是,Spring框架是一个非常庞大而复杂的项目,其源代码具有很高的复杂性和技术难度。如果您有兴趣深入了解Spring框架的源码,建议您从官方网站下载源代码并阅读相关文档,或者参考一些专门讲解Spring源码的书籍和教程。同时,熟悉Java编程、设计模式和IoC、AOP等基本概念也是理解和阅读Spring源码的基础。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值