如何在java中创建一个真正的单身人士?

如何在java中创建一个真正的单身人士?

问题描述:

在多个类加载器中使用时,我的单例遇到了问题.例如,由多个 EJB 访问的单例.有没有办法创建一个单例,它在所有类加载器中只有一个实例?

I am facing a problem with my singleton when used across multiple class loaders. E.g Singleton accessed by multiple EJBs. Is there any way to create a singleton which has only one instance across all class loader?

我正在寻找使用自定义类加载器或其他方式的纯 Java 解决方案.

I am looking for pure java solution either using custom class loader or some other way.

JavaEE 应用服务器通常通过将单例设置为服务"来解决这个问题,其确切的定义和配置取决于相关的应用服务器.

JavaEE app servers generally solve this problem by setting up the singleton as a "service", the exact definition and configuration of which depends on the appserver in question.

例如,在 JBoss 中,您可以使用 xyz-service.xml 描述符来设置挂在 JNDI 或 JMX 树上的单例对象,并且您的应用程序组件(例如您的 EJB)将从树中获取单例.这可以在一定程度上保护您免受底层类加载器语义的影响.

For example, in JBoss you could use a xyz-service.xml descriptor to set up a singleton object that hangs off the JNDI or JMX tree, and your application components (e.g. your EJBs) would fetch the singleton from the tree. That protects you to some extent from the underlying classloader semantics.