Best technique for getting the OSGi bundle context?

回眸只為那壹抹淺笑 提交于 2019-11-29 23:41:15
Ivan Dubrov

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

See FrameworkUtil JavaDoc.

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.

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.

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:

@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.

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).

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