Java 获取 OSGi 包上下文的最佳技术?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6527306/
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-16 06:40:03  来源:igfitidea点击:

Best technique for getting the OSGi bundle context?

javaosgi

提问by xconspirisist

Each bundle in my OSGi project has its own BundleActivator, which I think is normal. This gets passed the current BundleContext, which is useful to have around for getting service references and whatnot.

我的 OSGi 项目中的每个包都有自己的 BundleActivator,我认为这是正常的。这会传递当前的 BundleContext,这对于获取服务引用等很有用。

However, from classes in my bundle, how can I get the BundleContext? Assigning it to a public static field in the BundleActivator sucks and passing it around as an argument also sucks. Is there a more intelligent way?

但是,从我的包中的类,我怎样才能获得 BundleContext?将它分配给 BundleActivator 中的公共静态字段很糟糕,并将其作为参数传递也很糟糕。有没有更智能的方法?

采纳答案by Ivan Dubrov

You can use FrameworkUtil.getBundle(ClassFromBundle).getBundleContext().

您可以使用FrameworkUtil.getBundle(ClassFromBundle).getBundleContext().

See FrameworkUtil JavaDoc.

请参阅FrameworkUtil JavaDoc

回答by BJ Hargrave

There is no magic here. You need some way to provide the information to the other classes. So it is either available via the call stack or in some well known place (e.g. static).

这里没有魔法。您需要某种方式将信息提供给其他类。所以它可以通过调用堆栈或在一些众所周知的地方(例如静态)可用。

回答by RaduK

A good practice when developing OSGi bundles in my opinion is to try to write the OSGi related code as centralized as possible. This way, if you want to use your code in a non-OSGi environment, the migration effort is minimum.

在我看来,开发 OSGi 包时的一个好习惯是尝试编写尽可能集中的 OSGi 相关代码。这样,如果您想在非 OSGi 环境中使用您的代码,则迁移工作量最少。

Therefore, using static references or FrameworkUtil all over the place is not a good idea imho. Neither is using plain OSGi. Try to look at iPOJO or Declarative Services.

因此,恕我直言,到处使用静态引用或 FrameworkUtil 并不是一个好主意。也不使用普通的 OSGi。尝试查看 iPOJO 或声明式服务。

回答by Neil Bartlett

Another alternative is to use Declarative Services, which allows you to receive the BundleContext into your activator method. For example, assuming you use the Bnd Annotations for DS:

另一种选择是使用声明式服务,它允许您将 BundleContext 接收到您的激活器方法中。例如,假设您使用 DS 的 Bnd 注释:

@Activate
public void activate(BundleContext context) {
    // ...
}

However as RaduK said, it's much better if you can write the majority of your code in POJO style without using OSGi APIs such as BundleContext.

但是,正如 RaduK 所说,如果您可以在不使用诸如 BundleContext 之类的 OSGi API 的情况下以 POJO 风格编写大部分代码,那就更好了。