Bundle的源代码如下,需要导入felix.jar或者将其配置在CLASSPATH才能编译通过。

/*
* Apache Felix OSGi 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.");
}
}
}

Bundle的关键在于MANIFEST.MF文件,它存在于META-INF目录,内容如下

Bundle-Name: Service listener example
Bundle
-Description: A bundle that displays messages at startup and when service events occur
Bundle
-Vendor: Apache Felix
Bundle
-Version: 1.0.0
Bundle
-Activator: tutorial.example1.Activator
Import
-Package: org.osgi.framework

其中,Import-Package后面必须跟着换行符,否则这一行将被忽略,导致加载Bundle时无法找到依赖的包而加载失败。另外还需要注意的是类文件tutorial\example1\Activator.class是在打包后的jar文件的根目录下,而不是classes文件夹下,也就是和META-INF平级,否则将无法找到类文件。

一切完成后,可以将bundle的jar包example1.jar拷贝到热部署目录bundle然后运行java -jar bin\felix.jar,或者直接用gogo安装bundle(start file:/c:/example1.jar)。至此,第一个felix的bundle编写并安装完毕,它的作用是可以监听所有felix的注册、注销和修改事件,并打印。