【发布时间】:2017-01-22 11:44:41
【问题描述】:
我正在尝试使用 OSGi 框架开发一个简单的应用程序。我的问题涉及框架中可用的“实用程序包”:让我用一个非常冗长的例子来解释。目前我正在尝试构建一个我的捆绑包将发送的事件。
据我了解,我需要做以下事情(event admin felix):
public void reportGenerated(Report report, BundleContext context)
{
ServiceReference ref = context.getServiceReference(EventAdmin.class.getName());
if (ref != null)
{
EventAdmin eventAdmin = (EventAdmin) context.getService(ref);
Dictionary properties = new Hashtable();
properties.put("title", report.getTitle());
properties.put("path" , report.getAbsolutePath());
properties.put("time", System.currentTimeMillis());
Event reportGeneratedEvent = new Event("com/acme/reportgenerator/GENERATED", properties);
eventAdmin.sendEvent(reportGeneratedEvent);
}
}
现在,由于一个 OSGi 应用程序可能有很多包,我想为每个包创建一个 Event 的子类(例如,我有一个名为“BundleExample”的包?在它的导出类中会有一个“BundleExampleEvent”) .我知道这不会添加任何信息,因为您可以通过查看“主题”来知道您收到了哪个事件,但请暂时耐心等待。
现在,Event 构造函数需要一个主题和一个Map<String, Object>。但是,为了“简化”事件构造函数,我只想将主题和参数列表放入地图中。例如这里可能是一个 BundleExampleEvent 类:
public class BundleExampleEvent extends Event{
private int importantVariable;
public BundleExampleEvent(String topic, int importantVariable) {
super(topic, Utils.toMap("importantVariable", importantVariable));
//here toMap is static
}
public int getImportantVariable() {
return this.importantVariable;
}
}
好的,请注意Utils.toMap:这是一个允许您将String, Object 序列转换为Map 的函数。好的,现在Utils 是实用程序类的一个示例(愚蠢,无用,但仍然是实用程序类)。 本着 OSGi 的精神,我也想让这个实用程序类成为一个包:我的想法是在框架启动时启动这个 Utils 包,然后每当我需要它的一个实用程序时,我想获取一个通过@Reference注解引用。
这在任何捆绑接口实现中都可以很好地工作,如下所示:
@Component
public class BundleExampleImpl implements BundleExample {
@Reference
private Utils utils;
@Override
public String sayHello() {
return this.utils.fetchHello();
//another useless utility function, but hopefully it conveys what i'm trying to do
}
}
但是其他类(即在工作期间由 BundleExampleImpl 调用)呢?例如BundleExampleEvent 呢?我需要从sayHello 方法调用它,并且我想在该类中使用这个实用程序来计算地图!在前面的例子中我使用了一个静态函数,但是我想使用Utils OSGi 给我的引用。
当然,我可以在 BundleExampleEvent 的构造函数中添加一个参数以满足链接,但我宁愿不这样做,因为某些东西依赖于“实用程序类”非常愚蠢";我的问题是:
- 如果我想要“实用程序包”,这是唯一可用的方法吗?
-
或者我可以做一些奇怪的事情,比如在我的
BundleExampleEvent中添加 Utils 的引用;即这样的事情:public class BundleExampleEvent extends Event{ @Reference private Utils utils; private int importantVariable; public BundleExampleEvent(String topic, int importantVariable) { super(topic, Utils.toMap("importantVariable", importantVariable)); //here toMap is static } public int getImportantVariable() { return this.importantVariable; } } 或者也许拥有“实用程序包”的整个想法只是纯粹的垃圾?
感谢您的回复。希望我能以最清晰的方式表达我的问题
【问题讨论】:
标签: java osgi osgi-bundle