意义:直接使用编辑器编辑所需Osgi的服务,速度快、效率高。
OSGI容器:选择knopflerfish_osgi_5.1.0 (http://www.knopflerfish.org/),支持OSGI最新的R5标准。
方法:
1 在当前目录下编写Activator.java文件(不需要建立相应的包文件夹——省事),内容如下(这个参照Felix的tutorial)
package tutorial.example1; import org.osgi.framework.BundleActivator; import org.osgi.framework.BundleContext; import org.osgi.framework.ServiceListener; import org.osgi.framework.ServiceEvent; /** * This class implements a simple bundle that utilizes the OSGi * framework's event mechanism to listen for service events. Upon * receiving a service event, it prints out the event's details. **/ public class Activator implements BundleActivator, ServiceListener { /** * Implements BundleActivator.start(). Prints * a message and adds itself to the bundle context as a service * listener. * @param context the framework context for the bundle. **/ public void start(BundleContext context) { System.out.println("Starting to listen for service events."); context.addServiceListener(this); } /** * Implements BundleActivator.stop(). Prints * a message and removes itself from the bundle context as a * service listener. * @param context the framework context for the bundle. **/ public void stop(BundleContext context) { context.removeServiceListener(this); System.out.println("Stopped listening for service events."); // Note: It is not required that we remove the listener here, // since the framework will do it automatically anyway. } /** * Implements ServiceListener.serviceChanged(). * Prints the details of any service event from the framework. * @param event the fired service event. **/ public void serviceChanged(ServiceEvent event) { String[] objectClass = (String[]) event.getServiceReference().getProperty("objectClass"); if (event.getType() == ServiceEvent.REGISTERED) { System.out.println( "Ex1: Service of type " + objectClass[0] + " registered."); } else if (event.getType() == ServiceEvent.UNREGISTERING) { System.out.println( "Ex1: Service of type " + objectClass[0] + " unregistered."); } else if (event.getType() == ServiceEvent.MODIFIED) { System.out.println( "Ex1: Service of type " + objectClass[0] + " modified."); } } }
2 编写manifest.mf文件
Manifest-Version: 2.0 Bundle-Name: Service listener example——描述信息,用于查看该Bundle显示的标题) Bundle-Description: A bundle that displays messages at startup and when service events occur——bundle的简短说明信息 Bundle-Vendor: Knopflerfish Bundle-Version: 1.0.0 Bundle-Activator: tutorial.example1.Activator——完整类名,别写错了 Import-Package: org.osgi.framework
3 编写build.sh文件,内容为:
rm *.jar mkdir classes javac -d classes -cp ~/knopflerfish_osgi_5.1.0/osgi/framework.jar *.java jar cfm Hello.jar manifest.mf -C ./classes tutorial/example1
(Windows下编写build.bat文件,内容相应修改)
说明:
在jar命令行中,Hello.jar文件基本名随意取; ./classes与tutorial/example1之间有空格,表示在classes目录下,将tutorial/example1包下的class文件压缩入包。
4 运行knopflerfish容器
cd ~/knopflerfish_osgi_5.1.0/osgi
java -jar ./framework.jar
然后,将上述3步骤中的Hello.jar拖入窗口bundle区域,ok。
所述方法的好处:完全命令行,不需要借助第三方工具,开发具有敏捷特性。
时间: 2024-08-27 19:11:27