Skip to content

Commit

Permalink
update: add startup comments
Browse files Browse the repository at this point in the history
  • Loading branch information
ChlZhYa committed Aug 25, 2023
1 parent 43aa502 commit 55464a7
Show file tree
Hide file tree
Showing 8 changed files with 47 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -237,9 +237,11 @@ public Constructor<?>[] determineCandidateConstructors(Class<?> beanClass, Strin
return null;
}

// 提前 AOP
@Override
public Object getEarlyBeanReference(Object bean, String beanName) {
Object cacheKey = getCacheKey(bean.getClass(), beanName);
// 放入 AOP 集合中,当 BeanPostProcessor 的 postProcessAfterInitialization 方法执行时会用该集合判断是否还需要 AOP
this.earlyProxyReferences.put(cacheKey, bean);
return wrapIfNecessary(bean, beanName, cacheKey);
}
Expand Down Expand Up @@ -281,6 +283,7 @@ public PropertyValues postProcessProperties(PropertyValues pvs, Object bean, Str
}

/**
* 初始化后进行创建代理
* Create a proxy with the configured interceptors if the bean is
* identified as one to proxy by the subclass.
* @see #getAdvicesAndAdvisorsForBean
Expand Down Expand Up @@ -338,6 +341,7 @@ protected Object wrapIfNecessary(Object bean, String beanName, Object cacheKey)
}

// Create proxy if we have advice.
// 判断当前 Bean 是否需要 AOP
Object[] specificInterceptors = getAdvicesAndAdvisorsForBean(bean.getClass(), beanName, null);
if (specificInterceptors != DO_NOT_PROXY) {
this.advisedBeans.put(cacheKey, Boolean.TRUE);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,7 @@ public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFac
private ParameterNameDiscoverer parameterNameDiscoverer = new DefaultParameterNameDiscoverer();

/** Whether to automatically try to resolve circular references between beans. */
// 是否支持循环依赖。SpringBoot 2.6 开始默认不支持循环依赖
private boolean allowCircularReferences = true;

/**
Expand Down Expand Up @@ -579,6 +580,7 @@ protected Object doCreateBean(String beanName, RootBeanDefinition mbd, @Nullable
instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
}
if (instanceWrapper == null) {
// 通过构造方法构建实例
instanceWrapper = createBeanInstance(beanName, mbd, args);
}
Object bean = instanceWrapper.getWrappedInstance();
Expand All @@ -591,6 +593,8 @@ protected Object doCreateBean(String beanName, RootBeanDefinition mbd, @Nullable
synchronized (mbd.postProcessingLock) {
if (!mbd.postProcessed) {
try {
// 扩展点:MergedBeanDefinitionPostProcessor,对 BeanDefinition 进行处理
// 例如 AutowiredAnnotationBeanPostProcessor,针对 @Autowired 标记的方法和属性,会在这里寻找到所有的注入点
applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
}
catch (Throwable ex) {
Expand All @@ -610,13 +614,16 @@ protected Object doCreateBean(String beanName, RootBeanDefinition mbd, @Nullable
logger.trace("Eagerly caching bean '" + beanName +
"' to allow for resolving potential circular references");
}
// 将对象放到三级缓存中
addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
}

// Initialize the bean instance.
Object exposedObject = bean;
try {
// 填充属性
populateBean(beanName, mbd, instanceWrapper);
// 初始化 bean
exposedObject = initializeBean(beanName, exposedObject, mbd);
}
catch (Throwable ex) {
Expand Down Expand Up @@ -1796,10 +1803,12 @@ protected Object initializeBean(String beanName, Object bean, @Nullable RootBean

Object wrappedBean = bean;
if (mbd == null || !mbd.isSynthetic()) {
// 扩展点:初始化前处理逻辑 BeanPostProcessor::postProcessBeforeInitialization
wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
}

try {
// 调用初始化方法
invokeInitMethods(beanName, wrappedBean, mbd);
}
catch (Throwable ex) {
Expand All @@ -1808,6 +1817,7 @@ protected Object initializeBean(String beanName, Object bean, @Nullable RootBean
beanName, "Invocation of init method failed", ex);
}
if (mbd == null || !mbd.isSynthetic()) {
// 扩展点:初始化后处理逻辑 BeanPostProcessor::postProcessAfterInitialization
wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -78,15 +78,20 @@ public class DefaultSingletonBeanRegistry extends SimpleAliasRegistry implements
private final Map<String, Object> singletonObjects = new ConcurrentHashMap<>(256);

/** Cache of singleton factories: bean name to ObjectFactory. */
// 三级缓存。
// 存放原始对象,如果循环依赖中不需要进行 AOP 时,则直接从这里获取原始对象。
// 当循环依赖的对象需要 AOP 时,生成的代理对象的 target 属性需要指向原始对象。
private final Map<String, ObjectFactory<?>> singletonFactories = new HashMap<>(16);

/** Cache of early singleton objects: bean name to bean instance. */
// 没有经过完整声明周期的 Bean,实际上是构建方法执行后的原始对象或者 AOP 生成的代理对象,属性还没有填充。用于解决循环依赖
private final Map<String, Object> earlySingletonObjects = new ConcurrentHashMap<>(16);

/** Set of registered singletons, containing the bean names in registration order. */
private final Set<String> registeredSingletons = new LinkedHashSet<>(256);

/** Names of beans that are currently in creation. */
// 记录正在创建中的 Bean,用于处理循环依赖
private final Set<String> singletonsCurrentlyInCreation =
Collections.newSetFromMap(new ConcurrentHashMap<>(16));

Expand Down Expand Up @@ -179,19 +184,25 @@ public Object getSingleton(String beanName) {
@Nullable
protected Object getSingleton(String beanName, boolean allowEarlyReference) {
// Quick check for existing instance without full singleton lock
// 首先从一级缓存中判断是否已经有完整对象
Object singletonObject = this.singletonObjects.get(beanName);
// 如果没有完整实例并且在 beanName 当前正在创建中
if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) {
// 尝试从二级缓存中获取半成品 Bean
singletonObject = this.earlySingletonObjects.get(beanName);
// 如果二级缓存中也没有
if (singletonObject == null && allowEarlyReference) {
synchronized (this.singletonObjects) {
// Consistent creation of early reference within full singleton lock
singletonObject = this.singletonObjects.get(beanName);
if (singletonObject == null) {
singletonObject = this.earlySingletonObjects.get(beanName);
if (singletonObject == null) {
// 获取三级缓存中事先存入的 Lambda 表达式,执行后可以获得原始对象
ObjectFactory<?> singletonFactory = this.singletonFactories.get(beanName);
if (singletonFactory != null) {
singletonObject = singletonFactory.getObject();
// 将创建出来的对象放入到二级缓存中,同样将三级缓存删除,这样可以避免对象的重复创建
this.earlySingletonObjects.put(beanName, singletonObject);
this.singletonFactories.remove(beanName);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,7 @@ public AnnotatedBeanDefinitionReader(BeanDefinitionRegistry registry, Environmen
Assert.notNull(registry, "BeanDefinitionRegistry must not be null");
Assert.notNull(environment, "Environment must not be null");
this.registry = registry;
// @Conditional 注解解析器
this.conditionEvaluator = new ConditionEvaluator(registry, environment, null);
AnnotationConfigUtils.registerAnnotationConfigProcessors(this.registry);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ public class AnnotationConfigApplicationContext extends GenericApplicationContex
*/
public AnnotationConfigApplicationContext() {
StartupStep createAnnotatedBeanDefReader = this.getApplicationStartup().start("spring.context.annotated-bean-reader.create");
// BeanDefinitionReader
// BeanDefinitionReader,用于将注解类转换为 BeanDefinition,放入到 beanDefinitionMap 中
this.reader = new AnnotatedBeanDefinitionReader(this);
createAnnotatedBeanDefReader.end();
// 构造 Scanner,用于扫描 ClassPath 下的 Bean
Expand All @@ -91,6 +91,7 @@ public AnnotationConfigApplicationContext(DefaultListableBeanFactory beanFactory
*/
public AnnotationConfigApplicationContext(Class<?>... componentClasses) {
this();
// 注解配置类
register(componentClasses);
refresh();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,7 @@ public static Set<BeanDefinitionHolder> registerAnnotationConfigProcessors(
DefaultListableBeanFactory beanFactory = unwrapDefaultListableBeanFactory(registry);
if (beanFactory != null) {
if (!(beanFactory.getDependencyComparator() instanceof AnnotationAwareOrderComparator)) {
// 比较器,可以用来排序
beanFactory.setDependencyComparator(AnnotationAwareOrderComparator.INSTANCE);
}
if (!(beanFactory.getAutowireCandidateResolver() instanceof ContextAnnotationAutowireCandidateResolver)) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -550,34 +550,41 @@ public void refresh() throws BeansException, IllegalStateException {
prepareRefresh();

// Tell the subclass to refresh the internal bean factory.
// 获取 BeanFactory,对于 GenericApplicationContext 直接返回已经创建好的 beanFactory
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.
// 模板方法,对于 GenericApplicationContext 没有任何处理
postProcessBeanFactory(beanFactory);

StartupStep beanPostProcess = this.applicationStartup.start("spring.context.beans.post-process");
// Invoke factory processors registered as beans in the context.
// 使用 Scanner 扫描
// 使用 Scanner 扫描,解析 BeanDefinition 放入到 beanFactory 中
invokeBeanFactoryPostProcessors(beanFactory);

// Register bean processors that intercept bean creation.
// 注册 BeanPostProcessor
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.
Expand Down Expand Up @@ -636,6 +643,7 @@ protected void prepareRefresh() {

// Validate that all properties marked as required are resolvable:
// see ConfigurablePropertyResolver#setRequiredProperties
// 属性验证,校验程序设置的 requiredProperties 是否存在
getEnvironment().validateRequiredProperties();

// Store pre-refresh ApplicationListeners...
Expand Down Expand Up @@ -681,9 +689,11 @@ protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
// Tell the internal bean factory to use the context's class loader etc.
beanFactory.setBeanClassLoader(getClassLoader());
//SPEL 解析器
if (!shouldIgnoreSpel) {
beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));
}
// 添加一些默认支持的类型转换器
beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));

// Configure the bean factory with context callbacks.
Expand Down Expand Up @@ -717,9 +727,11 @@ protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
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());
}
// JVM 环境变量
if (!beanFactory.containsLocalBean(SYSTEM_ENVIRONMENT_BEAN_NAME)) {
beanFactory.registerSingleton(SYSTEM_ENVIRONMENT_BEAN_NAME, getEnvironment().getSystemEnvironment());
}
Expand Down Expand Up @@ -890,6 +902,7 @@ protected void registerListeners() {
*/
protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
// Initialize conversion service for this context.
// 类型转换处理
if (beanFactory.containsBean(CONVERSION_SERVICE_BEAN_NAME) &&
beanFactory.isTypeMatch(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)) {
beanFactory.setConversionService(
Expand All @@ -899,6 +912,7 @@ protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory b
// Register a default embedded value resolver if no BeanFactoryPostProcessor
// (such as a PropertySourcesPlaceholderConfigurer bean) registered any before:
// at this point, primarily for resolution in annotation attribute values.
// 占位符解析器
if (!beanFactory.hasEmbeddedValueResolver()) {
beanFactory.addEmbeddedValueResolver(strVal -> getEnvironment().resolvePlaceholders(strVal));
}
Expand All @@ -916,6 +930,7 @@ protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory b
beanFactory.freezeConfiguration();

// Instantiate all remaining (non-lazy-init) singletons.
// 实例化非懒加载单例 Bean
beanFactory.preInstantiateSingletons();
}

Expand All @@ -936,6 +951,7 @@ protected void finishRefresh() {
getLifecycleProcessor().onRefresh();

// Publish the final event.
// 发布容器启动完成事件
publishEvent(new ContextRefreshedEvent(this));

// Participate in LiveBeansView MBean, if active.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,7 @@ public GenericApplicationContext() {
*/
public GenericApplicationContext(DefaultListableBeanFactory beanFactory) {
Assert.notNull(beanFactory, "BeanFactory must not be null");
// 容器启动第一步,创建一个 BeanFactory
this.beanFactory = beanFactory;
}

Expand Down

0 comments on commit 55464a7

Please sign in to comment.