如何找出哪个包或插件调用了(共享)代码?
我想创建类似“BundleLocal”变量的内容,就像 ThreadLocal 变量一样,但我不是通过 Thread.currentThread()
查找它们需要通过捆绑上下文查找它们。
重点是我有一个框架插件“F”,以及使用该框架的其他插件“A”、“B”等。该框架包含一个单例,我想重构它,以便我每个包都有一个单例实例。然后,MySingleton.getInstance()
将为每个插件创建/返回一个专用实例。问题是在 MySingleton.getInstance()
中,我需要找出哪个插件('A'、'B'、..)调用了该方法。
我可以通过 hack 来实现,获取调用堆栈
StackTraceElement[] ste=new Throwable().getStackTrace();
,然后按每个元素的类查询包上下文:
org.osgi.framework.FrameworkUtil.getBundle(Class c).getBundleContext()
但真诚地希望存在更好的方法来获取包上下文或包 id在框架“F”内。
关于如何更优雅地做到这一点有什么建议吗?
I want to create something like 'BundleLocal' variables, just like ThreadLocal variables, but instead of looking them up by Thread.currentThread()
I need to look them up by bundle context.
The point is that I have a framework plugin 'F', and other plugins 'A', 'B', etc. using that framework. The framework contains a singleton which I want to refactor such that I have a singleton instance per bundle. MySingleton.getInstance()
would then create/return a dedicated instance for each plugin. The problem is that within MySingleton.getInstance()
I'd need to find out which of the plugins ('A', 'B', ..) called that method.
I could do it with a hack, obtaining the call stack with
StackTraceElement[] ste=new Throwable().getStackTrace();
and then querying the bundle context by class for each element:
org.osgi.framework.FrameworkUtil.getBundle(Class c).getBundleContext()
but sincerely hope that there exists a better way to obtain the bundle context or bundle id from within framework 'F'.
Any advice on how to do this more elegantly?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我建议从呼叫来源处注入信息,而不是尝试确定呼叫来源。像这样的东西:
I would recommend to inject the information from where the call comes instead of trying to determine where it comes from. Something like this:
由于 OSGi(及其隔离的类加载器)的模块化性质,单例不起作用(正如您所发现的)。
如果您要重构,一种选择是简单地添加间接。在 ActivatorA 中:
然后插件 A 使用 ActivatorA.getSingleton() ,插件 B 使用 ActivatorB.getSingleton() 。
另一种可能的方法是提供 ComponentFactory 并使用声明性服务将适当的组件(OSGi 服务)注入插件 A 和插件 B(每个人都获得自己的组件实例)。但这是我的第一个示例的更动态、更解耦的实现。
Because of the modular nature of OSGi (and its isolated class loaders) singletons don't work (as you found out).
If you're refactoring, one option would be to simply add indirection. In ActivatorA:
Then plugin A uses
ActivatorA.getSingleton()
and plugin B uses ActivatorB.getSingleton().The other potential way is to provide a ComponentFactory and use Declarative Service to inject the appropriate Component (OSGi service) into plugin A and plugin B (everybody gets their own instance of the Component). But this is a more dynamic, more decoupled implementation of my first example.