深入 Spring 源码熟悉单例
DefaultSingletonBeanRegistry 部分开放方法
使用单例的时候通常分为几个阶段
//存放单例的map
private final Map<String, Object> singletonObjects = new ConcurrentHashMap<>(256);
注册的时候会对bean进行一个判断,如果判断bean不存在才会进行添加。
public void registerSingleton(String beanName, Object singletonObject) throws IllegalStateException {
Assert.notNull(beanName, "Bean name must not be null");
Assert.notNull(singletonObject, "Singleton object must not be null");
synchronized (this.singletonObjects) {
Object oldObject = this.singletonObjects.get(beanName);
if (oldObject != null) {
throw new IllegalStateException("Could not register object [" + singletonObject +
"] under bean name '" + beanName + "': there is already object [" + oldObject + "] bound");
}
addSingleton(beanName, singletonObject);
}
}
下面这是我们添加单例的方法,通过加锁将我们的单例放到map中,然后通过getSingleton获取
protected void addSingleton(String beanName, Object singletonObject) {
synchronized (this.singletonObjects) {
this.singletonObjects.put(beanName, singletonObject);
this.singletonFactories.remove(beanName);
this.earlySingletonObjects.remove(beanName);
this.registeredSingletons.add(beanName);
}
}
获取到后再我们spring的getBean()方法中进行实例化,这样实例化后,我们就可以将我们的bean注册到我们的 map 中,其他的模块只需要通过beanName获取到注册的这一个对象。这样就达到了单例模式的效果。