Spring源码分析之AnnotationConfigApplicationContext

2022-06-15 12:29:19

AnnotationConfigApplicationContext

spring版本:5.2.8.RELEASE

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

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

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

AnnotationConfigApplicationContext annotationConfigApplicationContext=newAnnotationConfigApplicationContext(DemoConfig.class);

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

packagecom.mytest.spring;importorg.springframework.context.annotation.ComponentScan;importorg.springframework.context.annotation.Configuration;@ComponentScan("com.mytest.spring")@ConfigurationpublicclassDemoConfig{}

构造方法

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
	 */publicAnnotationConfigApplicationContext(Class<?>... componentClasses){this();register(componentClasses);refresh();}

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

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

this()

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

publicAnnotationConfigApplicationContext(){this.reader=newAnnotatedBeanDefinitionReader(this);this.scanner=newClassPathBeanDefinitionScanner(this);}

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

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

reader,重点关注

publicAnnotatedBeanDefinitionReader(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=newConditionEvaluator(registry, environment,null);AnnotationConfigUtils.registerAnnotationConfigProcessors(this.registry);}publicstaticSet<BeanDefinitionHolder>registerAnnotationConfigProcessors(BeanDefinitionRegistry registry,@NullableObject source){DefaultListableBeanFactory beanFactory=unwrapDefaultListableBeanFactory(registry);if(beanFactory!=null){if(!(beanFactory.getDependencyComparator()instanceofAnnotationAwareOrderComparator)){
				beanFactory.setDependencyComparator(AnnotationAwareOrderComparator.INSTANCE);}if(!(beanFactory.getAutowireCandidateResolver()instanceofContextAnnotationAutowireCandidateResolver)){
				beanFactory.setAutowireCandidateResolver(newContextAnnotationAutowireCandidateResolver());}}Set<BeanDefinitionHolder> beanDefs=newLinkedHashSet<>(8);if(!registry.containsBeanDefinition(CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME)){RootBeanDefinition def=newRootBeanDefinition(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=newRootBeanDefinition(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=newRootBeanDefinition(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=newRootBeanDefinition();try{
				def.setBeanClass(ClassUtils.forName(PERSISTENCE_ANNOTATION_PROCESSOR_CLASS_NAME,AnnotationConfigUtils.class.getClassLoader()));}catch(ClassNotFoundException ex){thrownewIllegalStateException("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=newRootBeanDefinition(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=newRootBeanDefinition(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()

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

@Overridepublicvoidrefresh()throwsBeansException,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();}}}

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

  • 作者:虎虎2022
  • 原文链接:https://blog.csdn.net/zhanghuyi2022/article/details/124368841
    更新时间:2022-06-15 12:29:19