在Spring中使用Java单例模式(对单例的静态访问)

实际的

考虑以下代码:

public class A {
    private static final A INSTANCE = new A();
    public static A getInstance() {
        return INSTANCE;
    }
    private A() {}
    public void doSomething() {}
}

// elsewhere in code
A.getInstance().doSomething();

当A需要使用构造弹簧豆时,我该怎么做?我不想在需要它的每个类中注入A,但希望这些类能够静态访问singleton实例(即A.getInstance())。

特比皮奇

从静态上下文访问Spring bean是有问题的,因为bean的初始化与它们的构造无关,并且Spring可以通过将它们包装在代理中来检测注入的bean。仅仅传递对的引用this通常会导致意外的行为。最好依靠Spring的注入机制。

如果确实需要执行此操作(也许是因为您需要从旧版代码进行访问),请使用以下方法:

@Service
public class A implements ApplicationContextAware {

    private static final AtomicReference<A> singleton;
    private static final CountDownLatch latch = new CountDownLatch(1);

    @Resource
    private MyInjectedBean myBean; // inject stuff...

    public static A getInstance() {
        try {
            if (latch.await(1, TimeUnit.MINUTES)) {
                return singleton.get();
            }
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
        throw new IllegalStateException("Application Context not initialized");
    }

    @Override
    public void setApplicationContext(ApplicationContext context) {
        singleton.set(context.getBean(A.class));
        latch.countDown();
    }
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章