OSGi Declarative Services Introduction

Declarative Services is a declarative model which provides a publish/find/bind model for using services. DS is a new service from OSGi R4.

DS simplifies the task of authoring services by performing the work of registering services and handling service dependencies.

DS helps de-couple service bundles from the OSGi framework and other service bundles. Service bundles don't need to provide a BundleActivator class to collaborate with other through the service registry.

To provide DS, a DS description file is necessary. I usually use OSGI-INF/service.xml.

Here is an example to declare a service and its referencing service:

<?xml version="1.0" encoding="UTF-8"?>
<component name="AuthServiceImpl">
    <implementation class="com.ibm.csdl.scakm.auth.impl.AuthServiceImpl"/>
    <reference name="useradmin" interface="org.osgi.service.useradmin.UserAdmin" bind="setUserAdmin" unbind="unsetUserAdmin"/>
    <service>
        <provide interface="com.ibm.csdl.scakm.auth.AuthService"/>
    </service>
</component>

A DS component has the following major parts:
1. service provided to service registry with specified interface (optional)
2. service implementation class or class factory (mandatory)
2. service references with specified interface (optional)

A bit like SCA model, huh?

The component class must implement the declared interface and at bundle startup time, the implementation will be registered in service registry to provide the capability of the interface. Sometimes the component needs to use services provided by other compnents, so it declares to find and bind those services by specified interfaces at startup time.

In the example, the component is implemented by AuthServiceImpl class, and offers service with com.ibm.csdl.scakm.auth.AuthService interface, and it references another service by interface org.osgi.service.useradmin.UserAdmin which is an OSGi standard service.

Let's see how another service uses the service in the example:

<?xml version="1.0" encoding="UTF-8"?>
<component name="AdminConsole">
    <implementation class="com.ibm.csdl.scakm.console.AdminCommandProvider"/>
    <reference name="auth" interface="com.ibm.csdl.scakm.auth.AuthService" bind="setAuthService" unbind="unsetAuthService"/>
</component>

Here the component doesn't provide a service to outside world, but only uses a service with interface com.ibm.csdl.scakm.auth.AuthService. At startup time, DS will resolve the reference between these two components, and set the AuthServiceImpl class instance to AdminCommandProvider.

你可能感兴趣的:(xml,IBM,osgi)