Spring source learning 16: creating a singleton bean

Programmer Xiaohang 2021-01-21 14:47:08
spring source learning creating singleton


Preface

stay finishBeanFactoryInitialization How to create Bean It's about the process , Here's the single example Bean The creation process of .

There are three parts to create a singleton Bean

  1. getSingleton
  2. createBean
  3. getObjectForBeanInstance

Now go to the source code :

getSingleton

public Object getSingleton(String beanName, ObjectFactory<?> singletonFactory) {
Assert.notNull(beanName, "Bean name must not be null");
// Lock
synchronized (this.singletonObjects) {
// Check singletonObjects Is there... In the cache
Object singletonObject = this.singletonObjects.get(beanName);
if (singletonObject == null) {
// Check if destruction is in progress
if (this.singletonsCurrentlyInDestruction) {
throw new BeanCreationNotAllowedException(beanName,
"Singleton bean creation not allowed while singletons of this factory are in destruction " +
"(Do not request a bean from a BeanFactory in a destroy method implementation!)");
}
if (logger.isDebugEnabled()) {
logger.debug("Creating shared instance of singleton bean '" + beanName + "'");
}
// take Bean Add to singletonsCurrentlyInCreation Collection , Indicates that you are creating
beforeSingletonCreation(beanName);
boolean newSingleton = false;
boolean recordSuppressedExceptions = (this.suppressedExceptions == null);
if (recordSuppressedExceptions) {
this.suppressedExceptions = new LinkedHashSet<>();
}
try {
// Call factory methods
// That is to call createBean(beanName, mbd, args)
singletonObject = singletonFactory.getObject();
newSingleton = true;
}
catch (IllegalStateException ex) {
// Has the singleton object implicitly appeared in the meantime ->
// if yes, proceed with it since the exception indicates that state.
singletonObject = this.singletonObjects.get(beanName);
if (singletonObject == null) {
throw ex;
}
}
catch (BeanCreationException ex) {
if (recordSuppressedExceptions) {
for (Exception suppressedException : this.suppressedExceptions) {
ex.addRelatedCause(suppressedException);
}
}
throw ex;
}
finally {
if (recordSuppressedExceptions) {
this.suppressedExceptions = null;
}
// Create success , from singletonsCurrentlyInCreation remove
afterSingletonCreation(beanName);
}
if (newSingleton) {
// Add the given singleton object to the singleton cache of the factory
// this.singletonObjects.put(beanName, singletonObject);
// this.singletonFactories.remove(beanName);
// this.earlySingletonObjects.remove(beanName);
// this.registeredSingletons.add(beanName);
addSingleton(beanName, singletonObject);
}
}
return singletonObject;
}
}

Returns... Registered with the given name ( original ) Singleton object , If not already registered , Then create and register a new object .

This piece can be divided into three parts to understand :

1. From the cache singletonObjects

singletonObject What is it? ?

/** Cache of singleton objects: bean name to bean instance. */
private final Map<String, Object> singletonObjects = new ConcurrentHashMap<>(256);

singletonObjects It's a ConcurrentHashMap, Used to cache instances of singleton objects .

2. establish singletonObject

In the cache did not get singletonObject , Create a new object

singletonObject = singletonFactory.getObject();

This step is actually to call the external createBean(beanName, mbd, args) Method , This is a factory approach . adopt createBean Method , It will create a new one singletonObject.

3. Will create the singletonObject Add to cache

protected void addSingleton(String beanName, Object singletonObject) {
synchronized (this.singletonObjects) {
this.singletonObjects.put(beanName, singletonObject);
this.singletonFactories.remove(beanName);
this.earlySingletonObjects.remove(beanName);
// Singletons that have been successfully created
this.registeredSingletons.add(beanName);
}
}

This step involves three caches , And a list of successfully created singletons .

/** Cache of singleton objects: bean name to bean instance. */
/** Cache singleton objects , K-V -> BeanName - Bean example */
private final Map<String, Object> singletonObjects = new ConcurrentHashMap<>(256);
/** Cache of singleton factories: bean name to ObjectFactory. */
/** cache Bean factory */
private final Map<String, ObjectFactory<?>> singletonFactories = new HashMap<>(16);
/** Cache of early singleton objects: bean name to bean instance. */
/** Cache early singleton objects */
private final Map<String, Object> earlySingletonObjects = new ConcurrentHashMap<>(16);
/** Set of registered singletons, containing the bean names in registration order. */
/** List of registered singletons , Save in order of registration BeanName. */
private final Set<String> registeredSingletons = new LinkedHashSet<>(256);

Singleton objects that will be created , Add to Single instance cache in , At the same time Factory cache as well as Early singleton object caching Delete the corresponding object in .

createBean

protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
throws BeanCreationException {
if (logger.isTraceEnabled()) {
logger.trace("Creating instance of bean '" + beanName + "'");
}
RootBeanDefinition mbdToUse = mbd;
// Make sure bean class is actually resolved at this point, and
// clone the bean definition in case of a dynamically resolved Class
// which cannot be stored in the shared merged bean definition.
// Get the real type
Class<?> resolvedClass = resolveBeanClass(mbd, beanName);
if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) {
// Create a new mbd prevent Other thread modifications
mbdToUse = new RootBeanDefinition(mbd);
mbdToUse.setBeanClass(resolvedClass);
}
// Prepare method overrides.
try {
// Verify and prepare for this bean Defined methods replace . Check if there is a method with the specified name .
mbdToUse.prepareMethodOverrides();
}
catch (BeanDefinitionValidationException ex) {
throw new BeanDefinitionStoreException(mbdToUse.getResourceDescription(),
beanName, "Validation of method overrides failed", ex);
}
try {
// Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.
// Post processor before application instantiation , To solve the specified bean Is there an instantiation shortcut .
// InstantiationAwareBeanPostProcessor Post Processors
// postProcessBeforeInstantiation Methods may have been instantiated Bean
Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
if (bean != null) {
return bean;
}
}
catch (Throwable ex) {
throw new BeanCreationException(mbdToUse.getResourceDescription(), beanName,
"BeanPostProcessor before instantiation of bean failed", ex);
}
try {
// Instantiation Bean
Object beanInstance = doCreateBean(beanName, mbdToUse, args);
if (logger.isTraceEnabled()) {
logger.trace("Finished creating instance of bean '" + beanName + "'");
}
return beanInstance;
}
catch (BeanCreationException | ImplicitlyAppearedSingletonException ex) {
// A previously detected exception with proper bean creation context already,
// or illegal singleton state to be communicated up to DefaultSingletonBeanRegistry.
throw ex;
}
catch (Throwable ex) {
throw new BeanCreationException(
mbdToUse.getResourceDescription(), beanName, "Unexpected exception during bean creation", ex);
}
}

This approach involves : establish Bean example , fill Bean , application PostProcessor.

Where instantiation Bean Is in doCreateBean in . Now let's focus on doCreateBean Method .

doCreateBean

protected Object doCreateBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
throws BeanCreationException {
// Instantiate the bean.
// Bean Of Object packaging
BeanWrapper instanceWrapper = null;
if (mbd.isSingleton()) {
// From the cache
instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
}
if (instanceWrapper == null) {
// If it is not available in the cache, it will be created directly , Created here BeanInstance !!!
instanceWrapper = createBeanInstance(beanName, mbd, args);
}
// obtain Bean Instance and type
Object bean = instanceWrapper.getWrappedInstance();
Class<?> beanType = instanceWrapper.getWrappedClass();
if (beanType != NullBean.class) {
mbd.resolvedTargetType = beanType;
}
// Allow post-processors to modify the merged bean definition.
synchronized (mbd.postProcessingLock) {
if (!mbd.postProcessed) {
try {
// If modification is allowed mbd
// call MergedBeanDefinitionPostProcessor Post processor
// postProcessMergedBeanDefinition(mbd, beanType, beanName);
applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
}
catch (Throwable ex) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"Post-processing of merged bean definition failed", ex);
}
mbd.postProcessed = true;
}
}
// Eagerly cache singletons to be able to resolve circular references
// even when triggered by lifecycle interfaces like BeanFactoryAware.
// mbd It's a singleton And Allow circular references to , ( Default true) And in creating
boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
isSingletonCurrentlyInCreation(beanName));
if (earlySingletonExposure) {
if (logger.isTraceEnabled()) {
logger.trace("Eagerly caching bean '" + beanName +
"' to allow for resolving potential circular references");
}
// First get Previous Bean References to , from beanPostProcessorCache in obtain SmartInstantiationAwareBeanPostProcessor
// And then from SmartInstantiationAwareBeanPostProcessor#getEarlyBeanReference Get the previous reference
addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
}
// Initialize the bean instance.
Object exposedObject = bean;
try {
// Attribute assignment
populateBean(beanName, mbd, instanceWrapper);
// perform init Method
exposedObject = initializeBean(beanName, exposedObject, mbd);
}
catch (Throwable ex) {
if (ex instanceof BeanCreationException && beanName.equals(((BeanCreationException) ex).getBeanName())) {
throw (BeanCreationException) ex;
}
else {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Initialization of bean failed", ex);
}
}
// Circular dependencies are allowed here
if (earlySingletonExposure) {
// Get the early Bean, If there is no circular dependency You can't get
Object earlySingletonReference = getSingleton(beanName, false);
// There are circular dependencies
if (earlySingletonReference != null) {
// Are you creating the same , There might be proxy objects
if (exposedObject == bean) {
exposedObject = earlySingletonReference;
}
else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {
// Get dependent on Bean and Loop into actualDependentBeans
String[] dependentBeans = getDependentBeans(beanName);
Set<String> actualDependentBeans = new LinkedHashSet<>(dependentBeans.length);
for (String dependentBean : dependentBeans) {
if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) {
actualDependentBeans.add(dependentBean);
}
}
if (!actualDependentBeans.isEmpty()) {
throw new BeanCurrentlyInCreationException(beanName,
"Bean with name '" + beanName + "' has been injected into other beans [" +
StringUtils.collectionToCommaDelimitedString(actualDependentBeans) +
"] in its raw version as part of a circular reference, but has eventually been " +
"wrapped. This means that said other beans do not use the final version of the " +
"bean. This is often the result of over-eager type matching - consider using " +
"'getBeanNamesForType' with the 'allowEagerInit' flag turned off, for example.");
}
}
}
}
// Register bean as disposable.
try {
// Register the destruction method
registerDisposableBeanIfNecessary(beanName, bean, mbd);
}
catch (BeanDefinitionValidationException ex) {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
}
return exposedObject;
}

It's also a long, long code !

Step by step :

If this Bean It's a singleton Bean And circular references are allowed and are being created , If there is a circular reference . Call :

addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));

This line of code involves two methods , Namely getEarlyBeanReference and addSingletonFactory

  • getEarlyBeanReference

  • addSingletonFactory

In this block, you can see the singletonFactory Added to the singletonFactories In cache .

At the same time earlySingletonObjects Singleton object removal from cache .

When will it be added to earlySingletonObjects In the cache ?

This can be referred to Spring Source code learning 15:finishBeanFactoryInitialization stay getSingleton In the method put In the .

For convenience , I'll post this little bit of code as well :

Here, cache from singletonFactories Moved to earlySingletonObjects.

Spring Of Bean The level 3 cache used in instantiation is actually :

singletonObjects: First level cache , Store singleton objects ,Bean Instantiated , Initialization complete .

earlySingletonObjects: Second level cache , Storage singletonObject, This Bean Instantiate , It's not initialized yet .

singletonFactories: Three level cache , Storage singletonFactory

The following initializes Bean

Here we focus on the following :

  • populateBean

Yes Bean The property of .

This one needs to be noted , When assigning a value to a property , I found that I depended on others Bean, I'm going to create something else first Bean.

The annotations I use here @Autowired You'll do the next part :

When parsing properties here , Will create internal dependencies Bean.

  • initializeBean

getObjectForBeanInstance

Get the given bean The object of the instance , If it is FactoryBean, Then for bean Instance itself or the object it creates .

This logic is relatively simple , It's based on what you created earlier beanInstance , Determine its type , Thus create Bean example .

summary

This paper mainly introduces a Single case Bean The creation of , Of course, it's all big pieces of source code , It takes patience .

Read the source code , Basically, you can have a detailed understanding of circular dependencies , know Spring Initializing Bean The third level cache is used to handle the amount of circular dependency , Later, we will prepare a separate article to introduce circular dependency .

Related to recommend

版权声明
本文为[Programmer Xiaohang]所创,转载请带上原文链接,感谢
https://javamana.com/2021/01/20210121144522343A.html

  1. 【计算机网络 12(1),尚学堂马士兵Java视频教程
  2. 【程序猿历程,史上最全的Java面试题集锦在这里
  3. 【程序猿历程(1),Javaweb视频教程百度云
  4. Notes on MySQL 45 lectures (1-7)
  5. [computer network 12 (1), Shang Xuetang Ma soldier java video tutorial
  6. The most complete collection of Java interview questions in history is here
  7. [process of program ape (1), JavaWeb video tutorial, baidu cloud
  8. Notes on MySQL 45 lectures (1-7)
  9. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  10. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  11. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  12. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  13. 【递归,Java传智播客笔记
  14. [recursion, Java intelligence podcast notes
  15. [adhere to painting for 386 days] the beginning of spring of 24 solar terms
  16. K8S系列第八篇(Service、EndPoints以及高可用kubeadm部署)
  17. K8s Series Part 8 (service, endpoints and high availability kubeadm deployment)
  18. 【重识 HTML (3),350道Java面试真题分享
  19. 【重识 HTML (2),Java并发编程必会的多线程你竟然还不会
  20. 【重识 HTML (1),二本Java小菜鸟4面字节跳动被秒成渣渣
  21. [re recognize HTML (3) and share 350 real Java interview questions
  22. [re recognize HTML (2). Multithreading is a must for Java Concurrent Programming. How dare you not
  23. [re recognize HTML (1), two Java rookies' 4-sided bytes beat and become slag in seconds
  24. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  25. RPC 1: how to develop RPC framework from scratch
  26. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  27. RPC 1: how to develop RPC framework from scratch
  28. 一次性捋清楚吧,对乱糟糟的,Spring事务扩展机制
  29. 一文彻底弄懂如何选择抽象类还是接口,连续四年百度Java岗必问面试题
  30. Redis常用命令
  31. 一双拖鞋引发的血案,狂神说Java系列笔记
  32. 一、mysql基础安装
  33. 一位程序员的独白:尽管我一生坎坷,Java框架面试基础
  34. Clear it all at once. For the messy, spring transaction extension mechanism
  35. A thorough understanding of how to choose abstract classes or interfaces, baidu Java post must ask interview questions for four consecutive years
  36. Redis common commands
  37. A pair of slippers triggered the murder, crazy God said java series notes
  38. 1、 MySQL basic installation
  39. Monologue of a programmer: despite my ups and downs in my life, Java framework is the foundation of interview
  40. 【大厂面试】三面三问Spring循环依赖,请一定要把这篇看完(建议收藏)
  41. 一线互联网企业中,springboot入门项目
  42. 一篇文带你入门SSM框架Spring开发,帮你快速拿Offer
  43. 【面试资料】Java全集、微服务、大数据、数据结构与算法、机器学习知识最全总结,283页pdf
  44. 【leetcode刷题】24.数组中重复的数字——Java版
  45. 【leetcode刷题】23.对称二叉树——Java版
  46. 【leetcode刷题】22.二叉树的中序遍历——Java版
  47. 【leetcode刷题】21.三数之和——Java版
  48. 【leetcode刷题】20.最长回文子串——Java版
  49. 【leetcode刷题】19.回文链表——Java版
  50. 【leetcode刷题】18.反转链表——Java版
  51. 【leetcode刷题】17.相交链表——Java&python版
  52. 【leetcode刷题】16.环形链表——Java版
  53. 【leetcode刷题】15.汉明距离——Java版
  54. 【leetcode刷题】14.找到所有数组中消失的数字——Java版
  55. 【leetcode刷题】13.比特位计数——Java版
  56. oracle控制用户权限命令
  57. 三年Java开发,继阿里,鲁班二期Java架构师
  58. Oracle必须要启动的服务
  59. 万字长文!深入剖析HashMap,Java基础笔试题大全带答案
  60. 一问Kafka就心慌?我却凭着这份,图灵学院vip课程百度云