Java EE 6 and Singletons

删除回忆录丶 提交于 2019-12-06 02:04:00

问题


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?

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?


回答1:


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

Yes! That's it! Just design the class like any other 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 @ApplicationScoped is been used.


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
private YourEJB yourEJB;



回答2:


The javax.ejb.Singleton annotation is used to specify that the enterprise bean implementation class is a singleton session 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:

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:

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

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


来源:https://stackoverflow.com/questions/18458631/java-ee-6-and-singletons

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!