我试图用OSGi框架开发一个简单的应用程序。我的问题涉及框架中的“实用程序包”:让我用一个相当详细的例子来解释。目前我正在尝试构建一个我的包将发送的事件。创建一个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应用程序可以有很多的包,我想创建事件的子类对于每个包(例如,我有一个名为“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
方法调用它,并且我想在该类中使用该实用程序来计算Map!在前面的例子中,我使用了一个静态函数,但是我想使用OSGi给我的Utils
的引用。
当然,我可以为了满足链接添加参数的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; } }
或者,也许有一个“工具包”的整体思路是只是纯粹的垃圾?
感谢您的回复。希望我能以最清晰的方式传达我的问题
静态链接是一个很好的概念,但我认为它不是很好理解用户。它也花了我一段时间来了解如何以及在何处使用它。也许值得一个博客条目,如果你还没有一个:-) –
@ChristianSchneider我做到了! http://njbartlett.name/2014/05/26/static-linking。html –
这就是我所希望的:-)谢谢 –