spring依赖注入的bean默认都是单例模式,他们是怎么创建的?
在AbstractBeanFactory类中的getBean方法中调用了getSingleton()方法来创建bean:
@Nullable 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; }
spring依赖注入时,使用了双重判断加锁的单例模式,首先从缓存MAP中获取bean实例,如果为null,对缓存map加锁,然后再从缓存中获取bean,如果继续为null,就创建一个bean。
Spring并没有使用私有构造方法来创建bean,而是通过singletonFactory.getObject()返回具体beanName对应的ObjectFactory来创建bean。实际上是调用了AbstractAutowireCapableBeanFactory的doCreateBean方法,返回了BeanWrapper包装并创建的bean实例。
看一下Netty实现的单例模式
public final class ReadTimeoutException extends TimeoutException { private static final long serialVersionUID = 169287984113283421L; public static final ReadTimeoutException INSTANCE = new ReadTimeoutException(); private ReadTimeoutException() { } }
类的定义十分简单,包含一个私有的构造函数和一个static final 实例 :这样其他的调用者如果想获取一个这个类的对象的话,访问不到私有的构造函数,而只能通过instance拿到对象。
使用static final的好处是:当类被调用的时候,static final会初始化,JNI会给这个类添加一个同步块,保证并发安全。
另外这种方式只有当类被调用的时候才会初始化一个实例。