Puede crear un objeto y registrarlo como un servicio OSGi para su uso en características de terceros.
Acerca de esta tarea
Mediante código Java anterior sin formato, puede crear un objeto y luego
registrarlo como un servicio utilizando la clase BundleContext.
Dado que se tiene que ejecutar el código, normalmente se registra el objeto en
una interfaz BundleActivator. Cuando registra el objeto, puede
especificar qué interfaces proporciona y suministrar una correlación de propiedades. Se devuelve un objeto ServiceRegistration; si es necesario, puede utilizar el objeto ServiceRegistration para cambiar las propiedades en cualquier momento. Cuando finaliza el servicio, se utiliza el objeto ServiceRegistration para anular el registro del servicio.
Para obtener un servicio, debe consultar en BundleContext un servicio que implemente una interfaz necesaria y, de manera opcional, proporcionar un filtro de sintaxis LDAP para que coincida con las propiedades del servicio. Dependiendo qué método invoque, puede recuperar la mejor coincidencia o todas las coincidencias. A continuación, puede utilizar la ServiceReference devuelta que proporciona las propiedades para buscar más coincidencias en el código. Puede utilizar ServiceReference para obtener el objeto de servicio real. Cuando termine de utilizar el servicio, utilice BundleContext para liberarlo.
- Declare la interfaz de servicio añadiendo el código siguiente en el paquete.
package com.ibm.foo.simple;
/**
* Nuestra interfaz de ejemplo multifuncional
*/
public interface Foo
{
}
- Especifique el código de implementación de la interfaz.
package com.ibm.foo.simple;
/**
* La implementación de la interfaz Foo
*/
public class FooImpl implements Foo
{
public FooImpl()
{
}
public FooImpl(String vendor)
{
}
/**
* used by the ServiceFactory implementation.
*/
public void destroy() {
}
}
- Utilice BundleContext para registrar el servicio, modificar las propiedades de servicio y anular el registro del servicio directamente en el código.
import java.util.Dictionary;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceRegistration;
/**
* Registers and unregsiters a Foo service directly,
* and shows how to modify the service properties in code.
*/
public class FooController
{
private final BundleContext bundleContext;
private ServiceRegistration<Foo> sr;
public FooController( BundleContext bundleContext )
{
this.bundleContext = bundleContext;
}
public void register(Dictionary<String, Object> serviceProperties) {
Foo foo = new FooImpl();
//typed service registration with one interface
sr = bundleContext.registerService( Foo.class, foo, serviceProperties );
//or
//untyped service registration with one interface
sr = (ServiceRegistration<Foo>)bundleContext.registerService(
Foo.class.getName(), foo, serviceProperties );
//or
//untyped service registration with more than one interface (or class)
sr = (ServiceRegistration<Foo>)bundleContext.registerService(new String[] {
Foo.class.getName(), FooImpl.class.getName()}, foo, serviceProperties );
}
public void modifyFoo(Dictionary<String, Object> serviceProperties) {
//with the service registration you can modify the service properties at any time
sr.setProperties( serviceProperties );
}
public void unregisterFoo() {
//when you are done unregister the service using the service registration
sr.unregister();
}
}
- Obtenga y devuelva el servicio desde otra clase:
package com.ibm.foo.simple;
import java.util.Collection;
import org.osgi.framework.BundleContext;
import org.osgi.framework.InvalidSyntaxException;
import org.osgi.framework.ServiceReference;
/**
* A simple Foo client that directly obtains the Foo service and returns it when done.
*/
public class FooUser
{
private final BundleContext bundleContext;
public FooUser( BundleContext bundleContext )
{
this.bundleContext = bundleContext;
}
/**
* assume there's only one Foo
*/
public void useFooSimple() {
ServiceReference<Foo> sr = bundleContext.getServiceReference( Foo.class );
String[] propertyKeys = sr.getPropertyKeys();
for (String key: propertyKeys) {
Object prop = sr.getProperty( key );
//think about whether this is the Foo we want....
}
Foo foo = bundleContext.getService( sr );
try {
//use foo
} finally {
//we're done
bundleContext.ungetService( sr );
}
}
/**
* Use a filter to select a particular Foo. Note we get a collection back and have to pick one.
* @throws InvalidSyntaxException
*/
public void useFooFilter() throws InvalidSyntaxException {
Collection<ServiceReference<Foo>> srs = bundleContext.getServiceReferences(
Foo.class, "(&(service.vendor=IBM)(id='myFoo')" );
ServiceReference<Foo> sr = srs.iterator().next();
String[] propertyKeys = sr.getPropertyKeys();
for (String key: propertyKeys) {
Object prop = sr.getProperty( key );
//think about whether this is the Foo we want....
}
Foo foo = bundleContext.getService( sr );
try {
//use foo
} finally {
//we're done
bundleContext.ungetService( sr );
}
}
}