前言:本篇只对主线核心逻辑进行梳理分析,本篇以AnnotationConfigApplicationContext容器为例进行切入分析【Spring版本为: v6.0.2】
一、实例化容器AnnotationConfigApplicationContext
我们启动容器的时候,虽然只是new了一个AnnotationConfigApplicationContext对象,但是在这个过程中spring处理了很多的事情。
创建AnnotationConfigApplicationContext对象
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MyConfig.class);
AnnotationConfigApplicationContext的类结构图如下:
进入AnnotationConfigApplicationContext类的有参构造函数
/**
* Create a new AnnotationConfigApplicationContext, deriving bean definitions
* from the given component classes and automatically refreshing the context.
* @param componentClasses one or more component classes — for example,
* {@link Configuration @Configuration} classes
*/
public AnnotationConfigApplicationContext(Class<?>... componentClasses) {
// 调用无参构造函数
this();
// 注册配置类为BeadDefinition
register(componentClasses);
// IOC容器刷新
refresh();
}
1、this()无参构造方法
无参构造中主要就是对读取器reader和扫描器scanner进行了实例化,reader是负责注解类型的Bean定义读取器,scanner的类型是ClassPathBeanDefinitionScanner,它仅仅是在外面手动调用.scan方法,或者调用参数为String的构造方法,传入需要扫描的包名才会用到。
/**
* Create a new AnnotationConfigApplicationContext that needs to be populated
* through {@link #register} calls and then manually {@linkplain #refresh refreshed}.
*/
// 调用本构造方法之前会先去调用父类GenericApplicationContext的构造函数
public AnnotationConfigApplicationContext() {
StartupStep createAnnotatedBeanDefReader = this.getApplicationStartup().start("spring.context.annotated-bean-reader.create");
// 创建一个读取注解的Bean定义的读取器,完成了spring内部BeanDefinition的注册
this.reader = new AnnotatedBeanDefinitionReader(this);
createAnnotatedBeanDefReader.end();
// 创建BeanDefinition扫描器,可以用来扫描包或者类,继而转换成bean定义
// 注意:spring默认的扫描包不是这个scanner对象,而是自己new的一个ClassPathBeanDefinitionScanner
this.scanner = new ClassPathBeanDefinitionScanner(this);
}
2、实例化Bean工厂:DefaultListableBeanFactory
上面源码中,会隐式调用父类的构造方法,即调用GenericApplicationContext的构造函数。在该构造方法中创建了beanFactory(DefaultListableBeanFactory),用来生产和获得Bean。
/**
* Create a new GenericApplicationContext.
* @see #registerBeanDefinition
* @see #refresh
*/
public GenericApplicationContext() {
// 为ApplicationContext spring上下文对象初始化beanFactory,
// DefaultListableBeanFactory在顶级接口BeanFactory基础上扩展了更多的功能,比如它实现了BeanDefinitionRegistry接口,拥有注册bean定义的能力
this.beanFactory = new DefaultListableBeanFactory();
}
DefaultListableBeanFactory类结构图:
- DefaultListableBeanFactory实现了BeanDefinationRegistry接口,具备了注册bean定义的能力。后面关于bean定义的注册就是该类负责
3、实例化BeanDefinition读取器:AnnotatedBeanDefinitionReader
/**
* Create a new {@code AnnotatedBeanDefinitionReader} for the given registry,
* using the given {@link Environment}.
* @param registry the {@code BeanFactory} to load bean definitions into,
* in the form of a {@code BeanDefinitionRegistry}
* @param environment the {@code Environment} to use when evaluating bean definition
* profiles.
* @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");
// 把ApplicationContext对象的registry,赋值给AnnotatedBeanDefinitionReader
this.registry = registry;
// 处理条件注解 @Condition
this.conditionEvaluator = new ConditionEvaluator(registry, environment, null);
// 注册一些spring的内置后置处理器
AnnotationConfigUtils.registerAnnotationConfigProcessors(this.registry);
}
4、创建BeanDefinition扫描器:ClassPathBeanDefinitionScanner
一般是不会用到AnnotationConfigApplicationContext里面的scanner的,这里的scanner 仅仅是为了程序员可以手动调用AnnotationConfigApplicationContext对象的scan方法。
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
context.scan();
5、注册配置类为BeanDefinition:register(annotatedClasses)
register是一开始提到的方法,我们分析下register(annotatedClasses)方法,其主要作用就是将配置类注册成bean定义。
/**
* Register one or more component classes to be processed.
* <p>Note that {@link #refresh()} must be called in order for the context
* to fully process the new classes.
* @param componentClasses one or more component classes — for example,
* {@link Configuration @Configuration} classes
* @see #scan(String...)
* @see #refresh()
*/
@Override
public void register(Class<?>... componentClasses) {
Assert.notEmpty(componentClasses, "At least one component class must be specified");
StartupStep registerComponentClass = this.getApplicationStartup().start("spring.context.component-classes.register")
.tag("classes", () -> Arrays.toString(componentClasses));
// 注册
this.reader.register(componentClasses);
registerComponentClass.end();
}
继续往下走,进入this.reader.register()
方法中
/**
* Register one or more component classes to be processed.
* <p>Calls to {@code register} are idempotent; adding the same
* component class more than once has no additional effect.
* @param componentClasses one or more component classes,
* e.g. {@link Configuration @Configuration} classes
*/
public void register(Class<?>... componentClasses) {
// 配置类可以传入多个,因此需要遍历注册
for (Class<?> componentClass : componentClasses) {
registerBean(componentClass);
}
}
继续进入registerBean()
方法中,然后进入doRegisterBean()
方法:
/**
* Register a bean from the given bean class, deriving its metadata from
* class-declared annotations.
* @param beanClass the class of the bean
* @param name an explicit name for the bean
* @param qualifiers specific qualifier annotations to consider, if any,
* in addition to qualifiers at the bean class level
* @param supplier a callback for creating an instance of the bean
* (may be {@code null})
* @param customizers one or more callbacks for customizing the factory's
* {@link BeanDefinition}, e.g. setting a lazy-init or primary flag
* @since 5.0
*/
private <T> void doRegisterBean(Class<T> beanClass, @Nullable String name,
@Nullable Class<? extends Annotation>[] qualifiers, @Nullable Supplier<T> supplier,
@Nullable BeanDefinitionCustomizer[] customizers) {
// 把传入的标记了注解的类转为AnnotatedGenericBeanDefinition数据结构,里面有一个getMetadata方法,可以拿到类上的注解
AnnotatedGenericBeanDefinition abd = new AnnotatedGenericBeanDefinition(beanClass);
// 判断是否需要跳过注解,spring中有一个@Condition注解,当不满足条件,这个bean就会跳过
if (this.conditionEvaluator.shouldSkip(abd.getMetadata())) {
return;
}
abd.setInstanceSupplier(supplier);
// 解析bean的作用域,如果没有配置,默认是单例
ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(abd);
abd.setScope(scopeMetadata.getScopeName());
String beanName = (name != null ? name : this.beanNameGenerator.generateBeanName(abd, this.registry));
// processCommonDefinitionAnnotations方法是解析通用注解,填充到AnnotatedGenericBeanDefinition,
// 解析的注解为Lazy,Primary,DependsOn,Role,Description
AnnotationConfigUtils.processCommonDefinitionAnnotations(abd);
if (qualifiers != null) {
for (Class<? extends Annotation> qualifier : qualifiers) {
if (Primary.class == qualifier) {
abd.setPrimary(true);
}
else if (Lazy.class == qualifier) {
abd.setLazyInit(true);
}
else {
abd.addQualifier(new AutowireCandidateQualifier(qualifier));
}
}
}
if (customizers != null) {
for (BeanDefinitionCustomizer customizer : customizers) {
customizer.customize(abd);
}
}
// 存放BeanDefinition、bean的名字还有bean的别名信息
BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(abd, beanName);
definitionHolder = AnnotationConfigUtils.applyScopedProxyMode(scopeMetadata, definitionHolder, this.registry);
// 注册,最终会调用DefaultListableBeanFactory中的registerBeanDefinition方法注册
// DefaultListableBeanFactory会维护一系列的信息,比如beanDefinitionNames、beanDefinitionMap
// beanDefinitionNames是一个List<String>,用于保存beanName, 最终将配置类的bean定义注册到beanDefinitionMap中
BeanDefinitionReaderUtils.registerBeanDefinition(definitionHolder, this.registry);
}
6、核心方法refresh()
其实至refresh方法调用前,Spring还没有进行扫描,只是实例化了一个工厂,注册了一些内置的Bean和我们传进去的配置类,最重要的处理过程就是在refresh方法中完成的。
refresh源码展示:
public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
StartupStep contextRefresh = this.applicationStartup.start("spring.context.refresh");
// 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);
StartupStep beanPostProcess = this.applicationStartup.start("spring.context.beans.post-process");
// Invoke factory processors registered as beans in the context.
invokeBeanFactoryPostProcessors(beanFactory);
// Register bean processors that intercept bean creation.
registerBeanPostProcessors(beanFactory);
beanPostProcess.end();
// 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();
contextRefresh.end();
}
}
}
6.1、 prepareRefresh()
该方法用于容器刷新前的准备,包括设置上下文状态,获取属性,验证必要的属性等。(核心部分的代码有中文说明)
/**
* Prepare this context for refreshing, setting its startup date and
* active flag as well as performing any initialization of property sources.
*/
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.
// 交给子类实现,初始化属性源
initPropertySources();
// Validate that all properties marked as required are resolvable:
// 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<>();
}
开发者可以实现initPropertySources()方法,添加属性或设置需要验证的属性(在执行验证属性时,将会校验是否有my-age配置),如下:
getEnvironment().setRequiredProperties("my-age");
6.2、obtainFreshBeanFactory()
该方法获取新的beanFactory。该方法很简单,刷新 BeanFactory 和获取 getBeanFactory。
/**
* Tell the subclass to refresh the internal bean factory.
* @return the fresh BeanFactory instance
* @see #refreshBeanFactory()
* @see #getBeanFactory()
*/
protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
// 刷新 BeanFactory
refreshBeanFactory();
// 获取 getBeanFactory
return getBeanFactory();
}
6.3、prepareBeanFactory(beanFactory)
该方法用于配置标准的 beanFactory ,设置 ClassLoader ,设置 SpEL 表达式解析器,添加忽略注入的接口,添加 bean ,添加 bean 后置处理器等。
/**
* Configure the factory's standard context characteristics,
* such as the context's ClassLoader and post-processors.
* @param beanFactory the BeanFactory to configure
*/
protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
// Tell the internal bean factory to use the context's class loader etc.
// 设置 beanFactory 的类加载器
beanFactory.setBeanClassLoader(getClassLoader());
// 设置支持表达式解析器
beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));
// 为 beanFactory 增加了一个默认的 propertyEditor ,这个主要是对 bean 的属性等设置管理的一个工具
beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));
// Configure the bean factory with context callbacks.
// 添加部分BeanPostProcessor【ApplicationContextAwareProcessor】
beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));
// 设置忽略的自动装配的接口EnvironmentAware、EmbeddedValueResolverAware、xxx
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()));
}
// Register default environment beans.
// 注册环境属性
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());
}
// 注册应用程序启动bean名称
if (!beanFactory.containsLocalBean(APPLICATION_STARTUP_BEAN_NAME)) {
beanFactory.registerSingleton(APPLICATION_STARTUP_BEAN_NAME, getApplicationStartup());
}
}
6.4、postProcessBeanFactory(beanFactory)
此时,所有的 beanDefinition 已经加载,但是还没有实例化允许在子类中对 beanFactory 进行扩展处理。比如添加 ware 相关接口自动装配设置,添加后置处理器等,是子类扩展 prepareBeanFactory(beanFactory) 的方法。
6.5、invokeBeanFactoryPostProcessors(beanFactory)
实例化并调用所有注册的beanFactory后置处理器(实现接口BeanFactoryPostProcessor的bean,在beanFactory标准初始化之后执行)。
/**
* Instantiate and invoke all registered BeanFactoryPostProcessor beans,
* respecting explicit order if given.
* <p>Must be called before singleton instantiation.
*/
protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) {
// 执行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()));
}
}
-
在invokeBeanFactoryPostProcessors方法中,Spring 会先去找到所有的实现了BeanDefinitionRegistryPostProcessor的 BeanFactory 后置处理器,然后先执行实现PriorityOrdered的,再执行实现了Ordered的。
-
其中最著名的就是ConfigurationClassPostProcessor,用来扫描被 @Component 和 @Bean 标记的对象,并注册其 BeanDefinition 元数据到 Spring 容器的 BeanDefinitionMap 中。然后再去获取所有的 BeanFactory 后置处理器,去掉已经执行过的,也是根据排序依次执行。该方法结束后,Spring 上下文中已经注册并执行了 BeanFactory 后置处理器,也将一部分 BeanDefinition 注册了进来。
6.6、注册 Bean 的后置处理器:registerBeanPostProcessors(beanFactory)
注册 Bean 的后置处理器,获取所有的 Bean 后置处理器的名字,对 Bean 后置处理器分类,执行完分类之后,所有的priorityOrderedPostProcessors都将成为一个 Bean 进入 Spring 容器中。由于源码比较乱,这里只整理出关键部分的代码:
// 1.获取所有的 Bean 后置处理器的名字
String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanPostProcessor.class, true, false);
// Register BeanPostProcessorChecker that logs an info message when
// a bean is created during BeanPostProcessor instantiation, i.e. when
// a bean is not eligible for getting processed by all BeanPostProcessors.
int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length;
beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount));
// 2.对 Bean 后置处理器分类
List<BeanPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
List<BeanPostProcessor> internalPostProcessors = new ArrayList<>();
List<String> orderedPostProcessorNames = new ArrayList<>();
List<String> nonOrderedPostProcessorNames = new ArrayList<>();
...
// First, register the BeanPostProcessors that implement PriorityOrdered.
sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
// 3.注册 Bean 后置处理器
registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors);
sortPostProcessors(orderedPostProcessors, beanFactory);
registerBeanPostProcessors(beanFactory, orderedPostProcessors);
registerBeanPostProcessors(beanFactory, nonOrderedPostProcessors);
// Finally, re-register all internal BeanPostProcessors.
sortPostProcessors(internalPostProcessors, beanFactory);
registerBeanPostProcessors(beanFactory, internalPostProcessors);
// Re-register post-processor for detecting inner beans as ApplicationListeners,
// moving it to the end of the processor chain (for picking up proxies etc).
beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext));
6.7、国际化处理:initMessageSource()
为上下文初始化 Message 源,对不同语言的消息体进行国际化处理。
6.8、初始化事件广播器:initApplicationEventMulticaster()
/**
* Initialize the ApplicationEventMulticaster.
* Uses SimpleApplicationEventMulticaster if none defined in the context.
* @see org.springframework.context.event.SimpleApplicationEventMulticaster
*/
protected void initApplicationEventMulticaster() {
ConfigurableListableBeanFactory beanFactory = getBeanFactory();
if (beanFactory.containsLocalBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME)) {
this.applicationEventMulticaster =
beanFactory.getBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, ApplicationEventMulticaster.class);
if (logger.isTraceEnabled()) {
logger.trace("Using ApplicationEventMulticaster [" + this.applicationEventMulticaster + "]");
}
}
else {
this.applicationEventMulticaster = new SimpleApplicationEventMulticaster(beanFactory);
beanFactory.registerSingleton(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, this.applicationEventMulticaster);
if (logger.isTraceEnabled()) {
logger.trace("No '" + APPLICATION_EVENT_MULTICASTER_BEAN_NAME + "' bean, using " +
"[" + this.applicationEventMulticaster.getClass().getSimpleName() + "]");
}
}
}
6.9、注册监听器:registerListeners()
/**
* Add beans that implement ApplicationListener as listeners.
* Doesn't affect other listeners, which can be added without being beans.
*/
protected void registerListeners() {
// 1. 添加指定的监听器
for (ApplicationListener<?> listener : getApplicationListeners()) {
getApplicationEventMulticaster().addApplicationListener(listener);
}
// 2. 获取所有实现 ApplicationListener 的广播器,并添加
String[] listenerBeanNames = getBeanNamesForType(ApplicationListener.class, true, false);
for (String listenerBeanName : listenerBeanNames) {
getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName);
}
// Publish early application events now that we finally have a multicaster...
Set<ApplicationEvent> earlyEventsToProcess = this.earlyApplicationEvents;
this.earlyApplicationEvents = null;
if (!CollectionUtils.isEmpty(earlyEventsToProcess)) {
for (ApplicationEvent earlyEvent : earlyEventsToProcess) {
getApplicationEventMulticaster().multicastEvent(earlyEvent);
}
}
}
6.10、finishBeanFactoryInitialization(beanFactory)
实例化所有剩余的非懒加载单例,比如invokeBeanFactoryPostProcessors方法中根据各种注解解析出来的类,在这个时候都会被初始化。实例化的过程各种BeanPostProcessor开始起作用。
// 1. 冻结所有的 bean,已经注册的 bean 定义将不会被修改或任何进一步的处理
beanFactory.freezeConfiguration();
// 2. 实例化所有剩余的非懒加载的 bean
beanFactory.preInstantiateSingletons();
// 获取容器中所有 beanDefinition 的名称
List<String> beanNames = new ArrayList<>(this.beanDefinitionNames);
for (String beanName : beanNames) {
// 根据 beanName 获取 BeanDefinition
RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
// 不是抽象的 && 是单例的 && 不是懒加载的
if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
if (isFactoryBean(beanName)) {
// 如果是 FactoryBean,就先获取 FactoryBean 实例
Object bean = getBean(FACTORY_BEAN_PREFIX + beanName);
if (bean instanceof SmartFactoryBean<?> smartFactoryBean && smartFactoryBean.isEagerInit()) {
getBean(beanName);
}
}
else {
// 如果不是 FactoryBean,就直接获取 Bean
getBean(beanName);
}
}
}
6.11、finishRefresh()
清除上下文资源缓存(如扫描中的ASM元数据)初始化上下文的生命周期处理器,并刷新,发布ContextRefreshedEvent事件告知对应的ApplicationListener进行响应的操作文章来源:https://www.toymoban.com/news/detail-401925.html
protected void finishRefresh() {
// Clear context-level resource caches (such as ASM metadata from scanning).
// 清除上下文资源缓存(如扫描中的ASM元数据) scanning).
clearResourceCaches();
// Initialize lifecycle processor for this context.
// 初始化上下文的生命周期处理器,并刷新(找出Spring容器中实现了Lifecycle接口的bean并执行start()方法)
initLifecycleProcessor();
// Propagate refresh to lifecycle processor first.
getLifecycleProcessor().onRefresh();
// Publish the final event.
// 发布ContextRefreshedEvent事件告知对应的ApplicationListener进行响应的操作
publishEvent(new ContextRefreshedEvent(this));
}
以上就是Spring 6 IOC容器加载过程与核心方法refresh源码浅析过程,希望对您有帮助。文章来源地址https://www.toymoban.com/news/detail-401925.html
到了这里,关于Spring 6 IOC容器加载过程与核心方法refresh源码浅析的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!