源码分析:Spring 单例轮子 - SingletonSupplier 发表于 2024-05-08 | 分类于 ---Spring , ---源码 | 123456789public class MyTest { // 2024-05-10 16:30 public static void main(String[] args) throws Throwable { SingletonSupplier<MyTest> supplier = SingletonSupplier.of(MyTest::new); supplier.get(); }} SingletonSupplier源码1234567891011121314151617181920212223242526272829303132333435363738394041424344/** * @since 5.1 */public class SingletonSupplier<T> implements Supplier<T> { @Nullable private final Supplier<? extends T> instanceSupplier; @Nullable private final Supplier<? extends T> defaultSupplier; @Nullable private volatile T singletonInstance; // ... @Override @Nullable public T get() { T instance = this.singletonInstance; if (instance == null) { synchronized (this) { instance = this.singletonInstance; if (instance == null) { if (this.instanceSupplier != null) { instance = this.instanceSupplier.get(); } if (instance == null && this.defaultSupplier != null) { instance = this.defaultSupplier.get(); } this.singletonInstance = instance; } } } return instance; } public T obtain() { T instance = get(); Assert.state(instance != null, "No instance from Supplier"); return instance; } // ...}