AnnotationConfigApplicationContext
对象/**
*
* 中文:
* 1、创建一个AnnotationConfigApplicationContext,用给定的bean生成一个bean的定义
* 2、自动刷新context
*/
public AnnotationConfigApplicationContext(Class<?>... componentClasses) {
/*
* 调用无参构造,内部具体进行一下逻辑操作:
*
* 1.创建一个新的AnnotationConfigApplicationContext
* 2.调用父类无参构造构造方法{@link GenericApplicationContext#GenericApplicationContext()}方法创建{@link DefaultListableBeanFactory}Bean工厂对象
* 3.创建BeanDefinition注册器的适配器,用于注册BeanDefinition,该适配器应用于带有某些注解类的注册工作
* 4.创建一个扫描类路径的BeanDefinition扫描器
*/
this();
//向注册器中注册给定的多个Class
register(componentClasses);
refresh();
}
/**
* 1.创建一个新的AnnotationConfigApplicationContext
* 2.调用父类无参构造构造方法{@link GenericApplicationContext#GenericApplicationContext()}方法创建{@link DefaultListableBeanFactory}Bean工厂对象
* 3.创建BeanDefinition注册器的适配器,用于注册BeanDefinition,该适配器应用于带有某些注解类的注册工作
* 4.创建一个扫描类路径的BeanDefinition扫描器
*/
public AnnotationConfigApplicationContext() {
//调用父类无参构造方法{@link GenericApplicationContext#GenericApplicationContext()},创建了DefaultListableBeanFactory工厂对象
super();
StartupStep createAnnotatedBeanDefReader = this.getApplicationStartup().start("spring.context.annotated-bean-reader.create");
//BeanDefinition注册器的适配器,用于注册BeanDefinition,该适配器应用于带有某些注解类的注册工作
this.reader = new AnnotatedBeanDefinitionReader(this);
createAnnotatedBeanDefReader.end();
this.scanner = new ClassPathBeanDefinitionScanner(this);
}
AnnotationConfigApplicationContext
,用给定的bean生成一个bean的定义。this()
无参构造函数,创建AnnotationConfigApplicationContext
对象。
AnnotationConfigApplicationContext
。{@link GenericApplicationContext#GenericApplicationContext()}
方法创建{@link DefaultListableBeanFactory}Bean
工厂对象。BeanDefinition
注册器的适配器,用于注册BeanDefinition
,该适配器应用于带有某些注解类的注册工作。ClassPathBeanDefinitionScanner
对象,用于扫描classpath
下的类,并转换成的BeanDefinition
注册到BeanDefinitionRegister
注册器中。Class
集合。**Spring**
(重要)。AnnotatedBeanDefinitionReader
对象/**
* 利用给定的Bean定义注册器(BeanDefinitionRegistry)创建一个新的AnnotatedBeanDefinitionReader()读取器
*
* @param registry Bean的注册器。BeanFactory利用BeanDefinitionRegistry来加载BeanDefinition(Bean定义)
* @see #AnnotatedBeanDefinitionReader(BeanDefinitionRegistry, Environment)
* @see #setEnvironment(Environment)
*/
public AnnotatedBeanDefinitionReader(BeanDefinitionRegistry registry) {
this(registry, getOrCreateEnvironment(registry));
}
/**
* 使用给定的 BeanDefinitionRegistry和Environment创建AnnotatedBeanDefinitionReader
*
* @param registry Bean工厂BeanFactory通过该BeanDefinitionRegistry注册器加载Bean定义
* @param environment 当前的系统环境数据。在Spring启动的时候会把系统环境数据全部加载进来,后续在用到系统环境数据的时候直接该对象中取
* @since 3.1
*/
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);
}
利用给定的Bean定义注册器(BeanDefinitionRegistry
)创建一个新的AnnotatedBeanDefinitionReader()
读取器,用于读取Class
,并封装成BeanDefinition
,然后注册到BeanDefinitionRegistry
中。
PostProcessor
/**
* Register all relevant annotation post processors in the given registry.
* @param registry the registry to operate on
*/
public static void registerAnnotationConfigProcessors(BeanDefinitionRegistry registry) {
registerAnnotationConfigProcessors(registry, null);
}
/**
* 向给定的BeanDefinitionRegistry注册器注册Spring内部底层用到所有对注解进行PostProcessor处理的后置处理器
*
* @param registry 注册器
* @param source the configuration source element (already extracted)
* that this registration was triggered from. May be {@code null}.
* @return 一个BeanDefinitionHolders集合, 包含了通过调用该方法注册的所有Bean定义
*/
public static Set<BeanDefinitionHolder> registerAnnotationConfigProcessors(
BeanDefinitionRegistry registry, @Nullable Object source) {
/*
* 获取Bean工厂BeanFactory
* 在创建 {@link AnnotationConfigApplicationContext}对象的时候
* 调用它父类{@link GenericApplicationContext}的{@link GenericApplicationContext#GenericApplicationContext()}
* 无参构造方法创建了{@link DefaultListableBeanFactory}工厂对象
*/
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());
}
}
/*
* 1.Bean持有器BeanDefinitionHolder集合。该BeanDefinitionHolder里边封装了BeanDefinition、Bean的名字、Bean的别名
* 2.每一个Bean持有器BeanDefinitionHolder对应一个BeanDefinition
*/
Set<BeanDefinitionHolder> beanDefs = new LinkedHashSet<>(8);
/*
* 1.将Spring内置后置处理器 {@link ConfigurationClassPostProcessor}封装成BeanDefinition
* 2.将ConfigurationClassPostProcessor对应的BeanDefinition注册到注册器中
*
* ConfigurationClassPostProcessor增强器作用:
* 1.找出带有@Configuration注解的Class
* 2.对带有@Configuration注解的Class进行postProcessor处理
*/
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));
}
/*
* 1.将Spring内置的AutowiredAnnotationBeanPostProcessor封装成BeanDefinition
* 2.将Spring内置的AutowiredAnnotationBeanPostProcessor对应的BeanDefinition注册到注册其中
*
* AutowiredAnnotationBeanPostProcessor的作用:
* 1.找出@Autowired、 @Value、 @jakarta.inject.Inject、 @javax.inject.Inject注解标记的类或者方法
* 2.对带有@Autowired、 @Value、 @jakarta.inject.Inject、 @javax.inject.InjectClass注解的Class或者Method进行postProcessor处理
*/
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));
}
/*
* 1.检查是否支持Jakarta Annotations注解
* 2.将Spring内置的CommonAnnotationBeanPostProcessor封装成BeanDefinition
* 3.将Spring内置的CommonAnnotationBeanPostProcessor对应的BeanDefinition注册到注册其中
*
* CommonAnnotationBeanPostProcessor作用:
* 1.找出带有@jakarta.annotation.Resource注解的类进行postProcessor处理
* 2.找出带有jakarta.annotation.PostConstruct和@jakarta.annotation.PreDestroy注解的方法,进行postProcessor处理
*
*/
if (jakartaAnnotationsPresent && !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 JSR-250 support, and if present add an InitDestroyAnnotationBeanPostProcessor
// for the javax variant of PostConstruct/PreDestroy.
/*
* 1.检查是否支持 JSR-250
* 2.将Spring内置的InitDestroyAnnotationBeanPostProcessor封装成BeanDefinition
* 3.将Spring内置的InitDestroyAnnotationBeanPostProcessor对应的BeanDefinition注册到注册其中
*
* InitDestroyAnnotationBeanPostProcessor作用:
* 2.找出带有@javax.annotation.PostConstruct和@javax.annotation.PreDestroy注解的方法,进行postProcessor处理
*/
if (jsr250Present && !registry.containsBeanDefinition(JSR250_ANNOTATION_PROCESSOR_BEAN_NAME)) {
try {
RootBeanDefinition def = new RootBeanDefinition(InitDestroyAnnotationBeanPostProcessor.class);
def.getPropertyValues().add("initAnnotationType", classLoader.loadClass("javax.annotation.PostConstruct"));
def.getPropertyValues().add("destroyAnnotationType", classLoader.loadClass("javax.annotation.PreDestroy"));
def.setSource(source);
beanDefs.add(registerPostProcessor(registry, def, JSR250_ANNOTATION_PROCESSOR_BEAN_NAME));
}
catch (ClassNotFoundException ex) {
// Failed to load javax variants of the annotation types -> ignore.
}
}
/*
* 1.检查是否支持 JPA
* 2.将Spring内置的PersistenceAnnotationBeanPostProcessor封装成BeanDefinition
* 3.将Spring内置的PersistenceAnnotationBeanPostProcessor对应的BeanDefinition注册到注册其中
*
* PersistenceAnnotationBeanPostProcessor作用:
* 2.找出带有@jakarta.persistence.PersistenceContext和@jakarta.persistence.PersistenceUnit注解的字段、方法,进行postProcessor处理
*/
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));
}
/*
* 1.将Spring内置的EventListenerMethodProcessor封装成BeanDefinition
* 2.将Spring内置的EventListenerMethodProcessor对应的BeanDefinition注册到注册其中
*
* EventListenerMethodProcessor作用:
* 1.找出带有@EventListener和@jakarta.persistence.PersistenceUnit注解的方法,进行postProcessor处理
*/
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));
}
/*
* 1.将Spring内置的DefaultEventListenerFactory封装成BeanDefinition
* 2.将Spring内置的DefaultEventListenerFactory对应的BeanDefinition注册到注册其中
*
* DefaultEventListenerFactory作用:
* 1.EventListenerMethodProcessor执行完postProcessor后,会对@EventListener注解标注方法所在的类创建一个代理类
* 2.利用上一步创建的代理类创建一个事件监听对象ApplicationListenerMethodAdapter
*/
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;
}
BeanDefinitionHolder
集合。每一个BeanDefinitionHolder
对应一个BeanDefinition
{@link ConfigurationClassPostProcessor}
ConfigurationClassPostProcessor增强器作用:
1.找出带有@Configuration注解的Class
2.对带有@Configuration注解的Class进行postProcessor处理
AutowiredAnnotationBeanPostProcessor
AutowiredAnnotationBeanPostProcessor增强器的作用:
1.找出@Autowired、 @Value、 @jakarta.inject.Inject、 @javax.inject.Inject标记的类或者方法
2.对带有@Autowired、 @Value、 @jakarta.inject.Inject、 @javax.inject.InjectClass注解的Class或者Method进行postProcessor处理
CommonAnnotationBeanPostProcessor
CommonAnnotationBeanPostProcessor作用:
1.找出带有@jakarta.annotation.Resource注解的类进行postProcessor处理
2.找出带有jakarta.annotation.PostConstruct和@jakarta.annotation.PreDestroy注解的方法,进行postProcessor处理
InitDestroyAnnotationBeanPostProcessor
InitDestroyAnnotationBeanPostProcessor作用:
1.找出带有@javax.annotation.PostConstruct和@javax.annotation.PreDestroy注解的方法,进行postProcessor处理
PersistenceAnnotationBeanPostProcessor
PersistenceAnnotationBeanPostProcessor作用:
1.找出带有@jakarta.persistence.PersistenceContext和@jakarta.persistence.PersistenceUnit注解的字段、方法,进行postProcessor处理
EventListenerMethodProcessor
EventListenerMethodProcessor作用:
1.找出带有@EventListener和@jakarta.persistence.PersistenceUnit注解的方法,进行postProcessor处理
DefaultEventListenerFactory
DefaultEventListenerFactory作用:
1.EventListenerMethodProcessor执行完postProcessor后,会对@EventListener注解标注方法所在的类创建一个代理类
2.利用上一步创建的代理类创建一个事件监听对象ApplicationListenerMethodAdapter
ClassPathBeanDefinitionScanner
对象/**
* 利用给定的BeanFactory创建一个新的ClassPathBeanDefinitionScanner对象
* @param registry 以BeanDefinitionRegistry的形式加载BeanDefinition到BeanFactory中
*/
public ClassPathBeanDefinitionScanner(BeanDefinitionRegistry registry) {
this(registry, true);
}
public ClassPathBeanDefinitionScanner(BeanDefinitionRegistry registry, boolean useDefaultFilters) {
this(registry, useDefaultFilters, getOrCreateEnvironment(registry));
}
public ClassPathBeanDefinitionScanner(BeanDefinitionRegistry registry, boolean useDefaultFilters,
Environment environment) {
this(registry, useDefaultFilters, environment,
(registry instanceof ResourceLoader resourceLoader ? resourceLoader : null));
}
public ClassPathBeanDefinitionScanner(BeanDefinitionRegistry registry, boolean useDefaultFilters,
Environment environment, @Nullable ResourceLoader resourceLoader) {
Assert.notNull(registry, "BeanDefinitionRegistry must not be null");
this.registry = registry;
if (useDefaultFilters) {
registerDefaultFilters();
}
setEnvironment(environment);
setResourceLoader(resourceLoader);
}
Environment
ResourceLoader
refresh()
方法刷新Spring
public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
StartupStep contextRefresh = this.applicationStartup.start("spring.context.refresh");
//刷新前的准备
prepareRefresh();
//获取并刷新BeanFactory
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
//初始化BeanFactory,也就是设置BeanFactory对象的一些属性值
prepareBeanFactory(beanFactory);
try {
//对BeanFactory进行PostProcessor处理
postProcessBeanFactory(beanFactory);
StartupStep beanPostProcess = this.applicationStartup.start("spring.context.beans.post-process");
/**
* 1.加载所有的Bean:触发{@link ClassPathBeanDefinitionScanner#doScan(String...)}方法执行,扫描@ComponetScan配置的包路径下的所有Class,封装成BeanDefinition放入{@link DefaultListableBeanFactory#beanDefinitionMap}BeanDefinitionMap中
* 2.所有的BeanFactoryPostProcessor注册到注册器
* 3.所有的BeanDefinitionRegisterPostProcessor注册到注册器
* 4.实例化所有的BeanFactoryPostProcessor和BeanDefinitionRegisterPostProcessor对象,放入Spring一级缓存中
* 注意:如果需要手动添加BeanFactoryPostProcessor一定在这个方法之前通过{@link addBeanFactoryPostProcessor}方法加入进来
*/
invokeBeanFactoryPostProcessors(beanFactory);
//Bean实例化之前,将所有的BeanPostProcessor注册到注册器
registerBeanPostProcessors(beanFactory);
beanPostProcess.end();
//初始化MessageSource
initMessageSource();
//初始化事件广播器
initApplicationEventMulticaster();
// Initialize other special beans in specific context subclasses.
//初始化特定上下文子类中的其他特殊bean。
onRefresh();
//检查监听Beans并注册他们
registerListeners();
//初始化剩下的所有单利(非懒加载)Bean
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();
contextRefresh.end();
}
}
}
prepareRefresh()
- 刷新前的准备。obtainFreshBeanFactory()
- 获取刷新的BeanFactory
。prepareBeanFactory(beanFactory);
- 初始化BeanFactory
,也就是设置BeanFactory
对象的一些属性值。postProcessBeanFactory(beanFactory)
- 对BeanFactory
进行PostProcessor
处理。invokeBeanFactoryPostProcessors(beanFactory)
- 执行所有的BeanFactoryPostProcessor
。registerBeanPostProcessors(beanFactory)
- 注册所有的BeanPostProcessor
。initMessageSource
- 初始化MessageSource
。initApplicationEventMulticaster
初始化事件广播器。registerListeners
- 注册监听器。finishBeanFactoryInitialization
- 初始化剩余的所有单利Bean
对象。finishRefresh
- 执行刷新完成逻辑。prepareRefresh()
protected void prepareRefresh() {
// Switch to active.
this.startupDate = System.currentTimeMillis();
this.closed.set(false);
this.active.set(true);
if (logger.isDebugEnabled()) {
if (logger.isTraceEnabled()) {
logger.trace("Refreshing " + this);
} else {
logger.debug("Refreshing " + getDisplayName());
}
}
// Initialize any placeholder property sources in the context environment.
//初始化属性资源(.properties文件)
initPropertySources();
// see ConfigurablePropertyResolver#setRequiredProperties
//检查必须属性是否已配置
getEnvironment().validateRequiredProperties();
// Store pre-refresh ApplicationListeners...
if (this.earlyApplicationListeners == null) {
this.earlyApplicationListeners = new LinkedHashSet<>(this.applicationListeners);
} else {
// Reset local application listeners to pre-refresh state.
this.applicationListeners.clear();
this.applicationListeners.addAll(this.earlyApplicationListeners);
}
// Allow for the collection of early ApplicationEvents,
// to be published once the multicaster is available...
this.earlyApplicationEvents = new LinkedHashSet<>();
}
PropertySources
。ApplicationListener
。ApplicationEvent
,一旦广播器可用就发布。BeanFactory
- obtainFreshBeanFactory()
/**
* Tell the subclass to refresh the internal bean factory.
*
* @return the fresh BeanFactory instance
* @see #refreshBeanFactory()
* @see #getBeanFactory()
*/
protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
refreshBeanFactory();
return getBeanFactory();
}
protected abstract void refreshBeanFactory() throws BeansException, IllegalStateException;
@Override
public abstract ConfigurableListableBeanFactory getBeanFactory() throws IllegalStateException;
BeanFactory
。以下为其子类:
AbstractRefreshableApplicationContext
GenericApplicationContext
BeanFactory
。BeanFactory
。BeanFactory
- prepareBeanFactory(beanFactory)
/**
* 配置BeanFactory
* 例如context的类加载器和PostProcessor
*
* @param beanFactory BeanFactory
*/
protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
//设置BeanFactory的Classloader
beanFactory.setBeanClassLoader(getClassLoader());
//设置SpEL表达式解析器
beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));
beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));
// Configure the bean factory with context callbacks.
beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));
//忽略依赖的接口
beanFactory.ignoreDependencyInterface(EnvironmentAware.class);
beanFactory.ignoreDependencyInterface(EmbeddedValueResolverAware.class);
beanFactory.ignoreDependencyInterface(ResourceLoaderAware.class);
beanFactory.ignoreDependencyInterface(ApplicationEventPublisherAware.class);
beanFactory.ignoreDependencyInterface(MessageSourceAware.class);
beanFactory.ignoreDependencyInterface(ApplicationContextAware.class);
beanFactory.ignoreDependencyInterface(ApplicationStartupAware.class);
// BeanFactory interface not registered as resolvable type in a plain factory.
// MessageSource registered (and found for autowiring) as a bean.
beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory);
beanFactory.registerResolvableDependency(ResourceLoader.class, this);
beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this);
beanFactory.registerResolvableDependency(ApplicationContext.class, this);
// Register early post-processor for detecting inner beans as ApplicationListeners.
beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this));
// Detect a LoadTimeWeaver and prepare for weaving, if found.
if (!NativeDetector.inNativeImage() && beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
// Set a temporary ClassLoader for type matching.
beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
}
//将默认的环境Bean对象注册到单例池中
if (!beanFactory.containsLocalBean(ENVIRONMENT_BEAN_NAME)) {
beanFactory.registerSingleton(ENVIRONMENT_BEAN_NAME, getEnvironment());
}
if (!beanFactory.containsLocalBean(SYSTEM_PROPERTIES_BEAN_NAME)) {
beanFactory.registerSingleton(SYSTEM_PROPERTIES_BEAN_NAME, getEnvironment().getSystemProperties());
}
if (!beanFactory.containsLocalBean(SYSTEM_ENVIRONMENT_BEAN_NAME)) {
beanFactory.registerSingleton(SYSTEM_ENVIRONMENT_BEAN_NAME, getEnvironment().getSystemEnvironment());
}
if (!beanFactory.containsLocalBean(APPLICATION_STARTUP_BEAN_NAME)) {
beanFactory.registerSingleton(APPLICATION_STARTUP_BEAN_NAME, getApplicationStartup());
}
}
BeanFactory
的ClassLoader
。BeanDefinition
中表达式的解析器。ApplicationContextAwareProcessor
,用于向应用暴露实现了Aware
接口的Spring
内部对象。Bean
。ApplicationListenerDetector
,用于检查内部的监听器 ApplicationListener
。Bean
对象注册到单例池中。包含 以下:
environment
- BeanFactory
中 {@link Environment
} bean
的名称systemProperties
- BeanFactory
中系统属性bean
的名称systemEnvironment
- BeanFactory
中系统环境bean
的名称applicationStartup
- BeanFactory
中 {@link ApplicationStartup
} bean
的名称BeanFactory
进行PostProcessor
在标准初始化后修改应用程序上下文的BeanFactory
。所有Bean
定义都已经被加载,但尚未实例化任何 bean
。这允许在某些 ApplicationContext
实现中注册特殊的BeanPostProcessor
等。
BeanFactoryPostProcessor
/**
* Instantiate and invoke all registered BeanFactoryPostProcessor beans,
* respecting explicit order if given.
* Must be called before singleton instantiation.
*
* 实例化并调用所有被注册进来的BeanFactoryPostProcessor对象
* 注意:必须在单利Bean实例化之前调用
*
* 1. 实例化所有的BeanFactoryPostProcessor和BeanDefinitionRegistryPostProcessor对象
* 2. 找出所有BeanDefinitionRegistryPostProcessor处理器,调用postProcessBeanDefinitionRegistry接口可BeanDefinition进行增强
* 2. 找出所有BeanFactoryPostProcessor处理器,调用postProcessBeanFactory接口对BeanFactory进行增强
*/
protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) {
//使用PostProcessor注解代理,调用所有的BeanFactoryPostProcessor对象
PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, getBeanFactoryPostProcessors());
// Detect a LoadTimeWeaver and prepare for weaving, if found in the meantime
// (e.g. through an @Bean method registered by ConfigurationClassPostProcessor)
if (!NativeDetector.inNativeImage() && beanFactory.getTempClassLoader() == null && beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
}
}
/**
* 执行BeanFactoryPostProcessor
*
* 1. 实例化所有的BeanFactoryPostProcessor和BeanDefinitionRegistryPostProcessor对象,并放入BeanFactory的一级缓存中
* 2. 找出所有BeanDefinitionRegistryPostProcessor处理器,按照优先级调用postProcessBeanDefinitionRegistry接口可BeanDefinition进行增强
* 2. 找出所有BeanFactoryPostProcessor处理器,按照优先级调用postProcessBeanFactory接口对BeanFactory进行增强
* 3. 解析配置类,解析配置类的注解、方法、Member来构建一个ConfigurationClass对象。
* 4. 根据ConfigurationClasses信息封装BeanDefinition,并注册到BeanRegister中,供后续使用。
*
* @param beanFactory Spring用到的工厂对象
* @param beanFactoryPostProcessors 通过手动调用{@link AbstractApplicationContext#addBeanFactoryPostProcessor(BeanFactoryPostProcessor)}
* 方法注册进来的BeanFactoryPostProcessor集合
*/
public static void invokeBeanFactoryPostProcessors(
ConfigurableListableBeanFactory beanFactory, List<BeanFactoryPostProcessor> beanFactoryPostProcessors) {
// WARNING: Although it may appear that the body of this method can be easily
// refactored to avoid the use of multiple loops and multiple lists, the use
// of multiple lists and multiple passes over the names of processors is
// intentional. We must ensure that we honor the contracts for PriorityOrdered
// and Ordered processors. Specifically, we must NOT cause processors to be
// instantiated (via getBean() invocations) or registered in the ApplicationContext
// in the wrong order.
//
// Before submitting a pull request (PR) to change this method, please review the
// list of all declined PRs involving changes to PostProcessorRegistrationDelegate
// to ensure that your proposal does not result in a breaking change:
// https://github.com/spring-projects/spring-framework/issues?q=PostProcessorRegistrationDelegate+is%3Aclosed+label%3A%22status%3A+declined%22
// Invoke BeanDefinitionRegistryPostProcessors first, if any.
Set<String> processedBeans = new HashSet<>();
//判断传入进来的工厂是否实现了BeanDefinitionRegistry接口。
//如果实现了BeanDefinitionRegistry接口,说明该工厂具备注册的功能,强转进行注册
if (beanFactory instanceof BeanDefinitionRegistry registry) {
List<BeanFactoryPostProcessor> regularPostProcessors = new ArrayList<>();
List<BeanDefinitionRegistryPostProcessor> registryProcessors = new ArrayList<>();
for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {
if (postProcessor instanceof BeanDefinitionRegistryPostProcessor registryProcessor) {
//修改Bean的标准初始化定义
registryProcessor.postProcessBeanDefinitionRegistry(registry);
registryProcessors.add(registryProcessor);
} else {
regularPostProcessors.add(postProcessor);
}
}
// Do not initialize FactoryBeans here: We need to leave all regular beans
// uninitialized to let the bean factory post-processors apply to them!
// Separate between BeanDefinitionRegistryPostProcessors that implement
// PriorityOrdered, Ordered, and the rest.
List<BeanDefinitionRegistryPostProcessor> currentRegistryProcessors = new ArrayList<>();
// First, invoke the BeanDefinitionRegistryPostProcessors that implement PriorityOrdered.
//获取所有的BeanDefinitionRegistryPostProcessor
String[] postProcessorNames =
beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
for (String ppName : postProcessorNames) {
//分离实现了PriorityOrdered接口的BeanDefinitionRegistryPostProcessor
if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
processedBeans.add(ppName);
}
}
//优先级1:执行实现了PriorityOrdered接口的BeanDefinitionRegistryPostProcessor方法,对存在于注册器里的BeanDefinition进行postProcessor处理
sortPostProcessors(currentRegistryProcessors, beanFactory);
registryProcessors.addAll(currentRegistryProcessors);
invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry, beanFactory.getApplicationStartup());
currentRegistryProcessors.clear();
// 再次获取所有的BeanDefinitionRegistryPostProcessor
postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
//分离实现了Ordered接口的BeanDefinitionRegistryPostProcessor
for (String ppName : postProcessorNames) {
//优先级1执行过的忽略掉
if (!processedBeans.contains(ppName) && beanFactory.isTypeMatch(ppName, Ordered.class)) {
currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
processedBeans.add(ppName);
}
}
sortPostProcessors(currentRegistryProcessors, beanFactory);
registryProcessors.addAll(currentRegistryProcessors);
//优先级2:执行实现了Ordered接口的BeanDefinitionRegistryPostProcessor#postProcessBeanDefinitionRegistry方法,对存在于注册器里的BeanDefinition进行postProcessor处理
invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry, beanFactory.getApplicationStartup());
currentRegistryProcessors.clear();
// Finally, invoke all other BeanDefinitionRegistryPostProcessors until no further ones appear.
//优先级2:执行剩下的BeanDefinitionRegistryPostProcessor方法,对存在于注册器里的BeanDefinition进行postProcessor处理
boolean reiterate = true;
while (reiterate) {
reiterate = false;
postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
for (String ppName : postProcessorNames) {
if (!processedBeans.contains(ppName)) {
currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
processedBeans.add(ppName);
reiterate = true;
}
}
sortPostProcessors(currentRegistryProcessors, beanFactory);
registryProcessors.addAll(currentRegistryProcessors);
invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry, beanFactory.getApplicationStartup());
currentRegistryProcessors.clear();
}
// Now, invoke the postProcessBeanFactory callback of all processors handled so far.
//最后,调用所有BeanFactoryPostProcessor#postProcessBeanFactory方法,对BeanFactory进行postProcessor处理。
invokeBeanFactoryPostProcessors(registryProcessors, beanFactory);
//手动注册进来的BeanFactoryPostProcessor
invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);
} else {
// Invoke factory processors registered with the context instance.
//调用已经被注册的BeanFactoryPostProcessor
invokeBeanFactoryPostProcessors(beanFactoryPostProcessors, beanFactory);
}
// Do not initialize FactoryBeans here: We need to leave all regular beans
// uninitialized to let the bean factory post-processors apply to them!
//获取所有的BeanFactoryPostProcessor
String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false);
/*
* 将实现了PriorityOrdered接口的BeanFactoryPostProcessor、实现了Ordered接口的BeanFactoryPostProcessor、未实现前两种的BeanFactoryPostProcessor拆分出来
*
* 调用BeanFactoryPostProcessor的优先级策略
*
* 优先级1:实现了PriorityOrdered接口的BeanFactoryPostProcessor
* 优先级2:实现了Ordered接口的BeanFactoryPostProcessor
* 优先级3:未实现以上两种接口的BeanFactoryPostProcessor
*/
//优先级1:实现了PriorityOrdered接口的BeanFactoryPostProcessor集合
List<BeanFactoryPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
//优先级2:实现了Ordered接口的BeanFactoryPostProcessor
List<String> orderedPostProcessorNames = new ArrayList<>();
//优先级3:未实现以上两种接口的BeanFactoryPostProcessor
List<String> nonOrderedPostProcessorNames = new ArrayList<>();
for (String ppName : postProcessorNames) {
if (processedBeans.contains(ppName)) {
// skip - already processed in first phase above
}
//BeanFactoryPostProcessor是否实现了PriorityOrdered接口
else if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
priorityOrderedPostProcessors.add(beanFactory.getBean(ppName, BeanFactoryPostProcessor.class));
}
//BeanFactoryPostProcessor是否实现了Ordered接口
else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
orderedPostProcessorNames.add(ppName);
}
//未实现前两种的BeanFactorPostProcessor
else {
nonOrderedPostProcessorNames.add(ppName);
}
}
//调用步骤一:
//调用实现了PriorityOrdered接口的BeanFactoryPostProcessor
sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
//执行BeanFactoryPostProcessor的postProcessBeanFactory方法
invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory);
//调用步骤二:
//调用实现了Ordered接口的BeanFactoryPostProcessor
List<BeanFactoryPostProcessor> orderedPostProcessors = new ArrayList<>(orderedPostProcessorNames.size());
for (String postProcessorName : orderedPostProcessorNames) {
//从工厂获取BeanFactoryPostProcessor对象
orderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
}
sortPostProcessors(orderedPostProcessors, beanFactory);
//执行BeanFactoryPostProcessor的postProcessBeanFactory方法
invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory);
//调用步骤三:
//调用剩余的BeanFactoryPostProcessor,也就是未实现前两种接口的BeanFactoryPostProcessor
List<BeanFactoryPostProcessor> nonOrderedPostProcessors = new ArrayList<>(nonOrderedPostProcessorNames.size());
for (String postProcessorName : nonOrderedPostProcessorNames) {
//从工厂获取BeanFactoryPostProcessor对象
BeanFactoryPostProcessor factoryPostProcessor = beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class);
nonOrderedPostProcessors.add(factoryPostProcessor);
}
//执行BeanFactoryPostProcessor的postProcessBeanFactory方法
invokeBeanFactoryPostProcessors(nonOrderedPostProcessors, beanFactory);
// Clear cached merged bean definitions since the post-processors might have
// modified the original metadata, e.g. replacing placeholders in values...
beanFactory.clearMetadataCache();
}