深入 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獲取到註冊的這一個對象。這樣就達到了單例模式的效果。