当前位置:首页 > 开发 > 编程语言 > Spring > 正文

spring单例bean实现原理

发表于: 2015-07-20   作者:嵇海波   来源:转载   浏览:
摘要: Spring 默认实例bean都是单例的  其中单例的实现原理: 定义一个final的ConcurrentHashMap对象,从而该域是线程安全的 privatefinal Map<String, Object> singletonObjects = new ConcurrentHashMap<String, Object>(64); 其

Spring 默认实例bean都是单例的  其中单例的实现原理:

定义一个final的ConcurrentHashMap对象,从而该域是线程安全的

privatefinal Map<String, Object> singletonObjectsnew ConcurrentHashMap<String, Object>(64);

其中获取单例的代码放置在同步块中,

protected Object getSingleton(String beanName, boolean allowEarlyReference) {

Object singletonObject = this.singletonObjects.get(beanName);

if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) {

synchronized (this.singletonObjects) {

singletonObject = this.earlySingletonObjects.get(beanName);

if (singletonObject == null && allowEarlyReference) {

ObjectFactory singletonFactory = this.singletonFactories.get(beanName);

if (singletonFactory != null) {

singletonObject = singletonFactory.getObject();

this.earlySingletonObjects.put(beanName, singletonObject);

this.singletonFactories.remove(beanName);

}

}

}

}

return (singletonObject != NULL_OBJECT ? singletonObject : null);

 

}

 

获取ClassLoader :Thread.currentThread().getContextClassLoader();

spring单例bean实现原理

  • 0

    开心

    开心

  • 0

    板砖

    板砖

  • 0

    感动

    感动

  • 0

    有用

    有用

  • 0

    疑问

    疑问

  • 0

    难过

    难过

  • 0

    无聊

    无聊

  • 0

    震惊

    震惊

版权所有 IT知识库 CopyRight © 2009-2015 IT知识库 IT610.com , All Rights Reserved. 京ICP备09083238号