Java EE 6 和单例

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18458631/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 01:47:30  来源:igfitidea点击:

Java EE 6 and Singletons

javaannotationssingletonjava-ee-6

提问by Peter Fox

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 @Singletonannotation? Do I have to do it this way?

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

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

这只是宣布它的一种情况,仅@Singleton此而已吗?我必须再上课吗?

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

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

回答by Juned Ahsan

The javax.ejb.Singletonannotation is used to specify that the enterprise bean implementation class is a singleton session bean.

javax.ejb.Singleton注释用于指定企业bean的实现类是单会话bean。

This information is to tell the ejb container, not to create multiple instance of this bean and only create a singleton instance. Otherwise it is just a normal bean class. Read more here:

这个信息是告诉ejb容器,不要创建这个bean的多个实例而只创建一个单例实例。否则它只是一个普通的 bean 类。在此处阅读更多信息:

http://docs.oracle.com/javaee/6/tutorial/doc/gipvi.html

http://docs.oracle.com/javaee/6/tutorial/doc/gipvi.html

You don't have to create a static variable, and do all the related stuff to make it singleton. Just write a normal bean as mentioned here and container will take care of instantiating only object of it:

你不必创建一个静态变量,并做所有相关的事情来使它成为单例。只需像这里提到的那样编写一个普通的 bean,容器将只负责实例化它的对象:

@Startup
@Singleton
public class StatusBean {
  private String status;

  @PostConstruct
  void init {
    status = "Ready";
  }
  ...
}

回答by BalusC

Is it just a case of declaring it @Singleton and that's it?

这只是声明@Singleton 的一个例子吗?

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

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

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 @ApplicationScopedis been used.

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



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

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

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

与其他所有 EJB 一样,通过将其注入为@EJB

@EJB
private YourEJB yourEJB;