OSGi教程 – 04 – 使用DS来处理事件
上一章中发布和处理事件都是使用API来完成,而根据前面的内容你已经知道可以使用DS通过XML配置来管理服务,下面我们来改造ServiceBundle的代码,使用DS来管理事件处理相关服务。
1.在第3章中的ServiceBundle的Activator类中删除注册EventHandler服务相关代码,将其修改成这样
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
package servicebundle; import org.osgi.framework.BundleActivator; import org.osgi.framework.BundleContext; import org.osgi.service.event.Event; import org.osgi.service.event.EventHandler; public class Activator implements BundleActivator, EventHandler { private static BundleContext context; static BundleContext getContext() { return context; } public void start(BundleContext bundleContext) throws Exception { Activator.context = bundleContext; } public void stop(BundleContext bundleContext) throws Exception { Activator.context = null; System.out.println("再见,OSGi的世界"); } // 监听到之后的处理 public void handleEvent(Event event) { System.out.println("监听到事件:" + event.getTopic()); } } |
2.在MANIFEST.MF中的Service-Component条目下增加OSGI-INF/eventhandler.xml,这样你的MANIFEST.MF看起来是这样的:
1 2 3 4 5 6 7 8 9 10 11 12 |
Manifest-Version: 1.0 Bundle-ManifestVersion: 2 Bundle-Name: ServiceBundle Plug-in Bundle-SymbolicName: ServiceBundle Bundle-Version: 1.0.0 Bundle-Activator: servicebundle.Activator Bundle-Vendor: Apollo Eclipse-LazyStart: true Import-Package: org.osgi.framework;version="1.3.0", org.osgi.service.event;version="1.1.0" Export-Package: servicebundle Service-Component: OSGI-INF/components.xml,OSGI-INF/eventhandler.xml |
3.在OSGI-INF文件夹下新建eventhandler.xml,内容如下:
1 2 3 4 5 6 7 8 9 10 11 |
<?xml version="1.0" encoding="UTF-8"?> <component name="EventHandler Example"> <implementation class="servicebundle.Activator" /> <service> <provide interface="org.osgi.service.event.EventHandler"/> </service> <property name="event.topics"> needservicebundle/WhoCare needservicebundle/AnyBody </property> </component> |
最后的运行效果应该跟第3章相同——显然使用DS使代码变得清爽多了。
打赏一下
支付宝

微信

除非注明,博客文章均为原创,转载请标明文章地址本文地址: http://www.javafxchina.net/blog/2016/07/osgi-04/