JBoss中如何获取单例实例?
我有一个必须在过滤器中实例化的单例,由于某种原因,我在第一次尝试时无法获得它的实例。 (部署在 JBoss EAP 5.1 中的应用程序)无需修改的相同解决方案也可以很好地与 Jetty 应用程序服务器配合使用。非常感谢您的提前答复。
此致,
罗马
I have a singleton that I have to instantiate in my filter and for some reason I cannot get it's instance on couple first attempts. (The application deployed in JBoss EAP 5.1) This same solution with no modification works just fine with Jetty Application server. Greatly appreciate for your answer in advance.
Sincerely,
Roman
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您不想使用任何依赖注入框架(Spring、Guice),请按照旧方式进行:
安装 ServletContextListener
在
contextInitialized(ServletContextEvent sce)
方法中创建您的单例并将其存储为属性ServletContext
当您的过滤器初始化时,您应该能够从过滤器的
FilterConfig
接口内传递的ServletContext
获取该单例实例。 初始化方法If you don't want to use any dependency injection framework ( Spring, Guice ), do it the old fashion way:
Install ServletContextListener
In
contextInitialized(ServletContextEvent sce)
method create your singleton and store it as an attribute onServletContext
When your filter will be initialized you should be able to get that singleton instance from the
ServletContext
that is passed inside theFilterConfig
interface in your filter's init method为什么你的过滤器中需要一个单例?您拥有网络应用程序、会话和请求上下文来放入您想要的任何数据。
也就是说,在没有看过你的代码的情况下,你有可能使用类静态变量来保存实例吗?如果是,请注意类的范围是由类加载器确定的,这就是为什么在应用程序服务器中使用此类习惯用法是一个坏主意的众多原因之一(这几乎可以保证使用类加载器层次结构来实现)等)JBoss 和 Jetty 显然有不同的方法。
Why do you need a singleton in your filter? You have web-app, session, and request contexts to put in any data you wish.
That said, without having seen your code it is ~100% likely you are using a class static variable to hold an instance? If yes, please note that classes are scoped by class-loaders, and this is one among many reasons why it is a bad idea to resort to such idioms in an application server (which pretty much is guaranteed to be implemented using class-loader hierarchies, etc.) JBoss and Jetty clearly have different approaches.