长治网站运营,公司理念网站,罗湖专业做网站公司,网站建设龙采科技spring依赖注入的bean默认都是单例模式#xff0c;他们是怎么创建的#xff1f;在AbstractBeanFactory类中的getBean方法中调用了getSingleton()方法来创建bean#xff1a;Nullableprotected Object getSingleton(String beanName, boolean allowEarlyReference) {Object si…spring依赖注入的bean默认都是单例模式他们是怎么创建的在AbstractBeanFactory类中的getBean方法中调用了getSingleton()方法来创建beanNullableprotected 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会给这个类添加一个同步块保证并发安全。另外这种方式只有当类被调用的时候才会初始化一个实例。