Java EE 6 和单例 [英] Java EE 6 and Singletons

查看:29
本文介绍了Java EE 6 和单例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

谁能解释在 Java EE 6 应用程序中实现单例的完整过程?我假设我不应该以声明静态变量的典型方式创建单例,而应该使用 @Singleton 注释?我必须这样做吗?

Can anyone explain the full process of implementing a Singleton in a Java EE 6 app? I'm assuming that I shouldn't be creating a singleton in the typical way of declaring a static variable and should be using the @Singleton annotation? Do I have to do it this way?

是否只是将其声明为 @Singleton 就这样?我还需要再上课吗?

Is it just a case of declaring it @Singleton and that's it? Do I have to do anymore to the class?

然后我需要做什么才能访问其他类中的单例?

What do I then need to do to access the singleton in my other classes?

推荐答案

这只是声明@Singleton 就这样吗?

是的!就是这样!只需像任何其他 Javabean 一样设计类即可.

Yes! That's it! Just design the class like any other Javabean.

但是请注意,这确实与 GoF 的单例设计模式不同.相反,它完全是只创建一个"模式.也许这就是你困惑的根源.诚然,注释名称的选择有些糟糕,在 JSF 和 CDI 中使用了名称 @ApplicationScoped.

Do however note that this is indeed not the same as GoF's Singleton design pattern. Instead, it's exactly the "just create one" pattern. Perhaps that's the source of your confusion. Admittedly, the annotation name is somewhat poorly chosen, in JSF and CDI the name @ApplicationScoped is been used.

然后我需要做什么才能访问其他类中的单例?

就像其他 EJB 一样,以 @EJB 的形式注入:

Just the same way as every other EJB, by injecting it as @EJB:

@EJB
private YourEJB yourEJB;

这篇关于Java EE 6 和单例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆